Searched: \.*

Results from TWiki web retrieved at 03:49 (GMT)

This is a short introductory training course for TWiki beginners.

Start Presentation

Slide 1: A Taste of TWiki

Hula girl The basic function of TWiki is a Wiki (if that helps!)

A Wiki is like a web site, except that you can edit the content in your browser

  • "Wiki" is short for "wiki wiki", the Hawaiian word for "Quick"
  • The idea originates from Macintosh Hypercard, via Ward Cunningham
  • In Ward's words, Wiki is "the simplest online database that could possibly work"
  • A Wiki is basically a shared, online, persistent whiteboard

Slide 2: TWiki Wiki

Whiteboard TWiki implements the basic Wiki idea of a shared whiteboard

  • Anyone can add content
    ... or change what is written
    ... or change the organisation of the content
  • Whatever you write is
    ... nicely presented
    ... remembered... and never forgotten

TWiki also acts as an "application platform" to integrate a number of other functions.

TWiki is an Open-Source development on TWiki.org

Slide 3: Where is it used?

TWiki is mainly used in commercial environments, often on corporate intranets
  • Examples: Disney, British Telecom, SAP, Wind River, Motorola, Epic Games
    Disney logo British Telecom logo SAP logo Motorola logo Epic Games logo

A number of public Wiki sites also use TWiki

Slide 4: TWiki Features

TWiki builds on the original Wiki concept and adds a number of features that make it very useful in a business environment.
  • TWiki pages are fully revision controlled, so a record of every change to every page is kept
    r6 < r5 < r4
  • The look-and-feel is highly configurable, through use of templates
  • A "plugins" interface eases
    • customisation
    • extension
    • application integration

Slide 5: Applications of basic TWiki

Basic TWiki can be used as:
  • A whiteboard
  • A document repository
  • A collaborative authoring environment
  • A notebook / scrapbook
  • A chat room

Slide 6: Extended applications

TWiki-with-extensions has been used as:
  • A Content Management System (CMS) for websites
  • A presentation development tool
  • A Blog
  • A database
  • A project management system
  • A tracking tool
  • (truth is, we don't really know its limits!)

Slide 7: Structure of a TWiki page

TWiki pages are usually organised into three parts:
  • A header
  • A body
  • A footer

  • The header and the footer are generated by the system
  • The body contains the text of the page, as entered by you
TWiki is very configurable, and the look can change. However the essentials will all be there on the page (somewhere!)

Slide 8: The Page Header

The header of a TWiki page is generally highlighted in colour, and will usually contain an icon that gives you an idea of where you are, such as a company logo.
TWiki home MyCo.MyTopic Webs:
Myco | Main | TWiki | Sandbox
Changes | Index | Search | Go
It will also usually contain a number of 'links' that you can click on. You will generally see:
  • Changes - gives you a list of recent changes
  • Index - gives you a full index
  • Search - takes you to a search page, where you can search all the text
  • Go - lets you type in the name of a page you already know

Slide 9: The Page Header ... continued

TWiki home MyCo.MyTopic Webs:
Myco | Main | TWiki | Sandbox
Changes | Index | Search | Go
You may also see in the header (usually at the top right) a list of the TWiki "webs". A web is a collection of pages that are related closely together
  • For example, we might have a web called "Enemies", where we keep all we know about our enemies, and another called "Friends"
  • There's usually a safe play web called something like "Sandbox" or "Scratch", where you can create pages just to try things out
  • And some admin areas, like "Main" and "TWiki"

Slide 10: The Page Footer

The footer of the page is also highlighted in colour, and is usually where you will find the links that let you change the content.
Edit | Attach | Diffs | r2 > r1 | More
Revision r1.2 - 13 Feb 2004 - 09:09 GMT - TWikiPresenter This site is powered by the TWiki collaboration platformCopyright © 1999-2024 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback
Note: Please contribute updates to this topic on TWiki.org at TWiki:TWiki.WebHome.
  • The Edit link takes you to an interactive page where you can change the page content
  • The Attach link lets you attach files
  • The other links invoke other, more complex, functions, mainly to do with revision tracking - they can safely be ignored for now

Slide 11: Editing Pages

  • You've read a page, and you disagree with it violently! It says:
    Everyone knows that the world is an OblateSpheroid
    But you know for a fact it is flat! wink
  • You've clicked the edit link, and an edit page has appeared. But it doesn't look much like what was on the page before - it's full of strange hieroglyphics!
_Everyone_ *knows* that =the world= is an OblateSpheroid
  • Now what?

Slide 12: What's in a page

  • The hieroglyphics are what's known as "TWiki Markup" or "formatting"
  • They are a really simple way of telling the browser how you want the page to look
  • You don't have to use them
    • TWiki understands pages in plain text just fine.

      Actually it is perfectly and absolutely flat

      appears as

      Actually it is perfectly and absolutely flat

Slide 13: Formatting just makes pages prettier

... and easier to read

_Actually_ it is *perfectly* and __absolutely__ flat

appears as

Actually it is perfectly and absolutely flat
  • A full description of all the formatting can be found in the TextFormattingRules and TextFormattingFAQ
  • The best thing to do is just to type until you get stuck
    • then follow the link on the edit page to the help.

Slide 14: Commonly used formatting

TWiki understands pages in plain text just fine, but you can jazz them up using some simple formatting shortcuts. Here are some of the more commonly used ones:
  • ---+ indicates a heading. Add more +'s for a deeper heading.
    You type You see
    ---+ This is a heading

    This is a heading

    ---++ And so is this

    And so is this

  • %TOC% will insert a table of contents

Slide 15: More common formatting

  • A blank line gives a paragraph break
  • --- on a line of its own gives a horizontal bar
  • Text in stars *like this* looks like this
  • Text in underscores _like this_ looks like this
  • Text in equals signs =like this= looks like this
  • Bulleted lists use three spaces followed by an asterisk (*) at the start of the line
    • The depth of the bullet is given by the number of spaces, in multiples of three
You type You see
   * Bullet
      * Sub-bullet
  • Bullet
    • Sub-bullet
  • Numbered lists use a number in place of the *. The list is numbered automatically, so you can just use a 1

Slide 16: Even more.....

  • You can create a table using vertical bars:
     | Cat | Feline |
     | Bear | Ursine |
     | Wolf | Lupine |
  • appears as
    Cat Feline
    Bear Ursine
    Wolf Lupine
  • %RED% .... %ENDCOLOR% will change the colour of the enclosed text. Lots of colours are available (%RED%, %GREEN%, %BLUE% etc)

WikiWords"> Slide 17: WikiWords

  • One special hieroglyph that is very important is a BumpyWord
    • a word that starts with uppercase, then some lowercase, then more uppercase (a.k.a CamelCase)
  • This has a special meaning to TWiki; if it matches the name of another topic, TWiki will automatically create a link to that page for you.
  • If there is no such page, then the word is highlighted with a red-link, LikeThis
  • If you click on the red-link, then TWiki will invite you to create that page.

  • This lets you enter the names of topics you think should exist, but don't yet
    • You, or someone else, can always come along later and click on the red-link!

Slide 18: Referencing other pages and URLs

  • BumpyWords automatically link to the target page
    • You can make these links easier to read using square brackets:
  • An ordinary URL pasted into text will appear as a link - http://www.google.com
    • You can also prettify URLs using square brackets:
      • [[http://www.google.com/][Google]] appears as Google
  • Use %SEARCH. This is an interface to a sophisticated search engine that embeds the results of the search in your page. See TWikiVariables for full details.

Slide 19: More formatting

  • There's lots more formatting available, see TextFormattingRules and TextFormattingFAQ
  • If you are a real masochist, you can even enter raw HTML tags!
  • Important to disable unwanted formatting, use <nop>
    • <nop>_word_ appears as _word_

Slide 20: Creating new pages

  • Alternative ways:
    • Click on the red-link of a BumpyWord
    • Type in the name of the topic in the "Jump" box
    • Type in the name of the topic in the URL
  • Any time you try to visit a page that doesn't exist, TWiki will invite you to create it.
  • Make sure the names of topics are always BumpyWords.

Slide 21: Attachments

  • Attachments are files which have been uploaded and attached to a TWiki page using the 'Attach' function in the footer.
Attachment sort Action Size Date Who Comment
myco.gif manage 9.6 K 13 Feb 2004 - 18:41 MushroomMagicMan Attached image file
  • Attachments are simply files, in whatever format you want.
  • TWiki recognises some file formats, notably image files (.gif)
    • Write %ATTACHURL%/myco.gif to see this: myco.gif

Slide 22: Wiki Culture

Enough about mechanics; how is a wiki actually used ? Well, that's really up to you, but there are a number of tricks that the wiki community has developed for collaborative writing that work pretty well:
  • What can I edit?
    • Anything. But it's good etiquette to sign your contributions
    • If someone doesn't want you to edit a page, it's up to them to say so, clearly, on the page
  • But what if somebody doesn't like my edits?
    • In TWiki, they can always recover the old revision and re-instantiate it if they really want to
    • Otherwise they should regard your changes as an opportunity for discussion
  • Pages in wiki are (usually) in one of three "modes"
    • DocumentMode
    • ThreadMode
    • StructuredMode
TWiki doesn't automatically distinguish between these modes; they are purely semantic.

DocumentMode"> Slide 23: DocumentMode

  • A page in DocumentMode usually comprises a contribution which is written in the third person and left unsigned.
  • The piece of text is community property
    • It may have multiple and changing authors as it is updated to reflect the community consensus.

ThreadMode"> Slide 24: ThreadMode

  • Thread mode is a form of discussion where the community holds a conversation
  • The discussion usually starts out with a statement, at the top of the page, that is subsequently discussed
  • The page may be periodically "refactored" (edited) to remove some of the comments
    • As long as the comment is accurately reflected in what replaces it, nobody usually minds.
    • Remember to always maintain a complete list of contributors, though!
You may see a comment box on a page in ThreadMode that makes it easy to quickly add your inputs. Typing in a comment and adding it to a page this way is known as "blogging" wink
  • ThreadMode is rather like an e-mail thread
    • Except that new comments are usually added to the end
  • ThreadMode pages often get refactored into DocumentMode

StructuredMode"> Slide 25: StructuredMode

  • A page in StructuredMode follows some predefined structure for example
    • An agenda
    • A set of meeting minutes
    • A requirement description.
  • Pages in StructuredMode will usually have rules governing how they are edited.

Slide 26: Other Wiki tricks - Categories

  • A Wiki trick for grouping pages together
  • Example: to group together a set of pages all relating to the weather:
    1. Create a page called 'CategoryWeather'
    2. Put a SEARCH that contains the word 'CategoryWeather' into it
      • %SEARCH{"CategoryWeather" nosearch="on" nosummary="on"}%
    3. Put the BumpyWord 'CategoryWeather' on all the pages relating to the weather
      (usually at the bottom, below a horizontal bar)

Slide 27: Contributed features

Basic TWiki is rich with features, but is enriched even further by the addition of optional plug-in modules that may (or may not!) be installed in your TWiki. These are classified as either skins (modules that change the look-and-feel) and plugins (modules that enhance functionality).

Here's a brief description of some of the more common plugins, together with the tags you might expect to see in topics if they are used. You can find out more by visiting the plugin pages.

  • AutoCompletePlugin: Auto-complete for input fields of forms
  • CalendarPlugin: Show a monthly calendar with highlighted events %CALENDAR...%
  • CommentPlugin: Support rapid entry of short comments (also known as blogging) %COMMENT...
  • ChartPlugin: Create PNG or GIF charts to visualize data in TWiki tables %CHART...
  • EditTablePlugin: Edit TWiki tables using edit fields and drop down boxes %EDITTABLE...
  • InterwikiPlugin: Define shortcuts for links to common external sites

Slide 28: More plugins

  • RenderListPlugin: Render bullet lists in a variety of formats %RENDERLIST...
  • SlideShowPlugin: Create web based presentations based on topics with headings %SLIDESHOWSTART...
  • SpreadSheetPlugin: Add spreadsheet calculations like "$SUM( $ABOVE() )" to tables located in TWiki topics %CALC...
  • TablePlugin: Control presentation and sorting of tables %TABLE...
  • TWikiDrawPlugin: Add quick sketches to pages %DRAWING...
The following plugins are installed on this TWiki: SpreadSheetPlugin, BackupRestorePlugin, ColorPickerPlugin, CommentPlugin, DatePickerPlugin, EditTablePlugin, HeadlinesPlugin, InterwikiPlugin, JQueryPlugin, PreferencesPlugin, RedirectPlugin, SetGetPlugin, SlideShowPlugin, SmiliesPlugin, TWikiSheetPlugin, TablePlugin, TagMePlugin, TinyMCEPlugin, TwistyPlugin, WatchlistPlugin, WysiwygPlugin

There are many other plugins, see http://TWiki.org/cgi-bin/view/Plugins

Slide 29: Credits and Acknowledgements

Related topics: WelcomeGuest, TWikiTutorial

Access Keys

What are access keys?

Access keys are keyboard shortcuts which allow the user to navigate around a website or a piece of computer software without having to use a mouse or other pointing device.

What are the advantages of using access keys?

Its an alternative to using a mouse, or other pointing device, and can sometimes be quicker than using a mouse.

Does TWiki have access keys?

TWiki offers access keys in view mode, such as "P" for printable view, and in edit mode, such as "S" for save. The underlined characters in topic action links indicate the access keys.

How do I use access keys?

This depends on the browser you are using:

  • Internet Explorer:
    • Press and hold the 'Alt' key
    • Press the required letter
    • Release the keys and press the 'ENTER' key

  • Netscape Navigator, Mozilla, or Firefox 1.0:
    • Press and hold the 'Alt' key
    • Press the required letter

  • Firefox 2.0 or later:
    • Press and hold both the 'Shift' and the 'Alt' key
    • Press the required letter

  • Firefox on Mac:
    • Press and hold the 'Ctrl' key
    • Press the required letter

  • Safari on Mac:
    • Press and hold both the 'Ctrl' and the key 'option' key
    • Press the required letter

Related Topics: UserDocumentationCategory

A List of TWiki Administrator Documentation

  • AdminSkillsAssumptions: Note: If you aren`t already fairly well skilled in Linux/Unix/Windows system administration...
  • AppendixEncodeURLsWithUTF8: Use internationalised characters within WikiWords and attachment names This topic...
  • EmptyPlugin: This is an empty plugin. Use it as a template to build your own .TWikiPlugins. This...
  • ForceNewRevision: Normally, if you make subsequent edits within a one hour period (configuration item...
  • HeadlinesPlugin: This plugin displays RSS and ATOM feeds from news sites. Use it to build news portals...
  • InstalledPlugins: Plugins are mainly user contributed add ons that enhance and extend TWiki features...
  • InstantEnhancements: These quick enhancements are aimed at improving and customising your TWiki. New...
  • InterWikis: This topic lists all aliases needed to map Inter Site links to external wikis/sites...
  • InterwikiPlugin: The InterwikiPlugin links ExternalSite:Page text to external sites based...
  • JQueryPlugin: This plugin contains the latest version of the jQuery JavaScript library....
  • MainFeatures: Any web browser: Edit existing pages or create new pages by using any web browser...
  • ManagingTopics: Browser based rename, move, and delete for individual topics Overview You can use...
  • ManagingWebs: Adding, renaming and deleting webs are all web based operations. Overview A TWikiSite...
  • PatternSkin: . For use in corporate or perhaps in personal websites it should be fairly easy to...
  • PatternSkinCss: This page is a reference for all CSS classes used in PatternSkin. PatternSkin uses...
  • PlainSkin: The plain skin is used to get the rendered topic text without any page decoration...
  • PreviewBackground: Preview looks like the real page, but the links lead to an oops dialog warning users...
  • PrintSkin: The print skin, useful to print pages with a small header and footer. Other skins...
  • RedirectPlugin: You can use this plugin to make easy to type shortforms/acronyms of topic names....
  • RenderListPlugin: Place a % RENDERLIST{ parameters before any bullet list The lists can...
  • SearchDoesNotWork: I`ve problems with the WebSearch. There is no Search Result on any inquiry....
  • SetGetPlugin: Use % SET{ to store arbitrary text in a named variable, and reuse it with % GET...
  • SitePermissions: Web Sitemap VIEW CHANGE RENAME Listed DENY ALLOW...
  • StandardColors: This table can be used to choose a color in of each web. #000000 #000033...
  • TWikiAccessControl: Restricting read and write access to topics and webs, by Users and groups TWiki...
  • TWikiAddOns: Add functionality to TWiki with extensions not based on the TWiki scripts. Overview...
  • TWikiContribs: Reusable code that may be used over several plugins and add ons. Overview TWiki...
  • TWikiCss: Listing of CSS class names emitted from TWiki core code and standard plugins. Who...
  • TWikiDocGraphics: This is the TWiki Documentation Graphics library. The graphics can be used in topics...
  • TWikiDocumentation: This page contains all documentation topics as one long, complete reference sheet...
  • TWikiDownload: I would like to install TWiki on my server. Can I get the source? Answer: TWiki...
  • TWikiInstallationGuide: The following is installation instructions for the TWiki 5.0 production release on...
  • TWikiNetSkin: The TWikiNetSkin is functional and clean and has corporate appeal. It is the default...
  • TWikiNetSkinPlugin: Helps TWikiNetSkin to render tables and h2 headers. This plugin is only enabled if...
  • TWikiPlugins: Add functionality to TWiki with readily available plugins; create plugins based on...
  • TWikiReferenceManual: Documentation for webmasters, system administrators, project managers, team leaders...
  • TWikiScripts: Programs on the TWiki server performing actions such as rendering, saving and renaming...
  • TWikiSiteTools: Utilities for searching, navigation, and monitoring site activity TWiki Site Tools...
  • TWikiSkinBrowser: You can try out the TWikiSkins currently installed on this system: .skinstable td...
  • TWikiSkins: Skins overlay regular templates to give different looks and feels to TWiki screens...
  • TWikiSystemRequirements: Server and client requirements Low client and server base requirements are core...
  • TWikiTemplates: Definition of the templates used to render all HTML pages displayed in TWiki Overview...
  • TWikiTopics: The basic building block of a TWiki site is called a topic , identified by a unique...
  • TWikiUpgradeGuide: This guide covers upgrading from a previous version of TWiki (such as TWiki 4.3)...
  • TWikiUserAuthentication: TWiki site access control and user activity tracking options Overview Authentication...
  • TagMePlugin: Plugin to tag wiki content collectively in order to find content by tags and to get...
  • TimeSpecifications: TWiki recognizes the following formats for date/time strings. For all strings the...
  • TopMenuSkin: The TopMenuSkin adds pulldown menus to the PatternSkin. Screen Shot Tob Bar and...
  • TwistyPlugin: The TwistyPlugin gives you several options to control the appearance of a twisty...
  • WebLeftBar: 1 Web Users Groups Index Search Changes...
  • WebTopMenu: This topic defines the menu structure of the TWiki web, used by the TopMenuSkin...

Related topics: AdminToolsCategory, CategoryCategory, DeveloperDocumentationCategory, UserDocumentationCategory, UserToolsCategory

Administrator Skills Assumptions

Note: If you aren't already fairly well-skilled in Linux/Unix/Windows system administration, Apache webserver configuration, and so on, consider using TWiki:Codev.TWikiVMDebianStable - this can be installed on Windows or Linux, and makes it possible to get a working TWiki system within 5 minutes (after a fairly big download), ready to use from your browser. This is ideal for personal use or evaluations - if you decide to go for production use then these AdminSkillsAssumptions apply to some degree, but you are starting from a working system.

If you need to install TWiki you'll need to either have or learn the following skills (even with TWikiVMDebianStable, you'll need these for upgrades). For each of these, the requirement is either pre-existing knowledge/skill, or the willingness to spend significant time (i.e. from hours to days) learning them:

  • Operating system administration: Ability to use Unix/Linux command line tools (or equivalent Windows tools), including ability to move/copy/delete files, change permissions, view web server log files, set environment variables, use a text editor, etc.
  • Web server administration: Ability to do basic setup, e.g. ability to edit config files or use GUI configuration tools to enable CGI scripts on a directory.
  • Program compilation: Where Revision Control System (RCS) is not pre-installed (that is most Unix systems), the ability to download and compile the RCS program from source, including use of configure, make, etc. This is often not necessary on Linux or Windows.
  • Troubleshooting: Ability to perform tests, inspect error logs, talk to technical support (whether in an IT department or web hosting provider) and read documentation in order to help with diagnosing installation problems.

Installing TWiki is not recommended for people who only know HTML and web design, unless they are willing to learn the above, or team up with someone who can handle the installation.

Although the TWikiInstallationGuide is quite complete, there will on occasion be parts that don't work in your local environment (particularly with TWiki:Codev/TWikiOnWebHostingSites, which are sometimes challenging even for those with good OS and web server skills).

There are many excellent resources for learning how to administer your OS and web server, including books, web sites, web forums, IM and e-mail lists.

To get started with Linux, visit LinuxBasics.org. LinuxBasics.org offers Linux tutorials, a mailing-list and an IRC-channel to answer questions, and links to sites with information to install and use Linux. LinuxBasics.org now also offers a downloadable Linux 'virtual machine' (LBox) that runs on Windows - you can use this as a completely safe learning environment, and feel free to make mistakes without any chance of damaging your Windows setup.

Some resources if you need help, or want to get up and running quickly:

  • TWiki:Support/WebHome: Post a question in the TWiki.org support forum. This forum is mainly intended for TWiki related issues, there are other forums if you need help in operating system and web server administration.
  • TWiki:Codev/TWikiIRC: Get help from the TWiki community in the #twiki IRC channel.
  • TWiki:Codev/TWikiConsultants: Hire a consultant to get you up to speed, maintain or customize your TWiki installation.
  • TWiki OnSite: A VMware based TWiki distribution with support, adding Enterprise Social Networking and other Enterprise 2.0 applications.
  • TWiki OnDemand: A TWiki hosting solution with support, adding Enterprise Social Networking and other Enterprise 2.0 applications.

Related Topics: AdminDocumentationCategory

Admin Tools

Manage whole TWiki site from one screen.

All Admin Tools Category topics

  • BackupRestoreConsole: Related Topics: BackupRestorePlugin, .AdminToolsCategory
  • BackupRestorePlugin: This is a solution to backup, restore, and upgrade TWiki sites. It can be used via the browser and on...
  • BulkRegistration: Administrators can use this topic to register (i.e. create logins and user topics) for a group of people...
  • ChangeEmailAddress: This form is used to change your registered e mail addresses. Your registered e mails are used by TWiki...
  • EditUserAccount: WikiName of user: find users Related topics: ManagingUsers, QueryUsers, AdminToolsCategory
  • InstalledPlugins: Plugins are mainly user contributed add ons that enhance and extend TWiki features and capabilities....
  • ManagingUsers: Register users on your TWiki site; change/reset/install passwords; remove user accounts Some of the...
  • ManagingWebs: Adding, renaming and deleting webs are all web based operations. Overview A TWikiSite is divided into...
  • QueryUsers: Find users: show all clear Related topics: ManagingUsers, EditUserAccount, AdminToolsCategory...
  • ResetPassword: Remember your password? Use 1 instead. Otherwise, use this form to get a new one e mailed to you...
  • SiteMap: TWiki is divided up into webs, also known as workspaces or collaboration spaces. Web Description...
  • SitePermissions: Web Sitemap VIEW CHANGE RENAME Listed DENY ALLOW DENY ALLOW...
  • SiteStatisticsTemplate: NOTE: This is a template topic, do not change. Update the site statistics. Monthly Site Statistics Data...
  • TWikiReferenceManual: Documentation for webmasters, system administrators, project managers, team leaders, and all other users...
  • TWikiSiteTools: Utilities for searching, navigation, and monitoring site activity TWiki Site Tools include utilities...
  • TemplateWeb: Template webs contain a set of default topics and act as templates when creating a new web. Names of...
  • WebHome: The official TWiki site is twiki.org Welcome to the TWiki Documentation Web The place to learn about...
  • WebLeftBar: 1 Web Users Groups Index Search Changes Notifications...
  • WebTopMenu: This topic defines the menu structure of the TWiki web, used by the TopMenuSkin . 1...

Plugins

Administrators can enable and disable plugins using configure.

  • SpreadSheetPlugin (2018-07-05, $Rev: 30478 (2018-07-16) $): Add spreadsheet calculation like "$SUM( $ABOVE() )" to TWiki tables or anywhere in topic text
  • BackupRestorePlugin (2021-03-19, $Rev: 30914 (2021-03-19) $): Administrator utility to backup, restore and upgrade a TWiki site
  • ColorPickerPlugin (2018-07-05, $Rev: 30442 (2018-07-16) $): Color picker, packaged for use in TWiki forms and TWiki applications
  • CommentPlugin (2018-07-05, $Rev: 30530 (2018-07-16) $): Quickly post comments to a page without an edit/preview/save cycle
  • DatePickerPlugin (2018-07-05, $Rev: 30446 (2018-07-16) $): Pop-up calendar with date picker, for use in TWiki forms, HTML forms and TWiki plugins
  • EditTablePlugin (2018-07-05, $Rev: 30448 (2018-07-16) $): Edit TWiki tables using edit fields, date pickers and drop down boxes
  • HeadlinesPlugin (2018-07-13, $Rev: 30560 (2018-07-16) $): Show headline news in TWiki pages based on RSS and ATOM news feeds from external sites
  • InterwikiPlugin (2018-07-05, $Rev: 30454 (2018-07-16) $): Write ExternalSite:Page to link to a page on an external site based on aliases defined in a rules topic
  • JQueryPlugin (2018-07-05, $Rev: 30456 (2018-07-16) $): jQuery JavaScript library for TWiki
  • PreferencesPlugin (2018-07-05, $Rev: 30528 (2018-07-16) $): Allows editing of preferences using fields predefined in a form
  • RedirectPlugin (2015-12-02, $Rev: 29697 (2015-12-03) $): Create a redirect to another topic or website
  • SetGetPlugin (2018-07-05, $Rev: 30472 (2018-07-16) $): Set and get variables and JSON objects in topics, optionally persistently across topic views
  • SlideShowPlugin (2018-07-05, $Rev: 30474 (2018-07-16) $): Create web based presentations based on topics with headings.
  • SmiliesPlugin (2018-07-05, $Rev: 30476 (2018-07-16) $): Render smilies as icons, like  :-) for smile or  :eek: for eek!
  • TWikiSheetPlugin (2018-07-15, $Rev: 30604 (2018-07-16) $): Add TWiki Sheet spreadsheet functionality to TWiki tables
  • TablePlugin (2018-07-05, $Rev: 30480 (2018-07-16) $): Control attributes of tables and sorting of table columns
  • TagMePlugin (2018-07-05, $Rev: 30482 (2018-07-16) $): Tag wiki content collectively or authoritatively to find content by keywords
  • TinyMCEPlugin (2021-06-09, $Rev: 31045 (2021-06-09) $): Integration of the Tiny MCE WYSIWYG Editor
  • TwistyPlugin (2018-07-06, $Rev: 30497 (2018-07-16) $): Twisty section JavaScript library to open/close content dynamically
  • WatchlistPlugin (2018-07-10, $Rev: 30536 (2018-07-16) $): Watch topics of interest and get notified of changes by e-mail
  • WysiwygPlugin (2018-07-06, $Rev: 30528 (2018-07-16) $): Translator framework for WYSIWYG editors

See also: TWikiPlugins

TWiki Version

  • TWiki engine: TWiki-6.1.0, Mon, 16 Jul 2018, build 30610
  • Plugin API: 6.10

Related topics: AdminDocumentationCategory, CategoryCategory, DeveloperDocumentationCategory, UserDocumentationCategory, UserToolsCategory

FAQ:

How can I create a simple TWiki Forms based application?

Answer:

TWiki applications help automate workflows you have at the workplace. TWiki has a built-in database that can be used to write custom web applications. These are wiki applications that run in TWiki.

A typical TWiki forms based application consists of the following pages:

  • Application home page, typically containing links to other application pages. It may contain also a report showing data records.
  • Form definition page, defining the fields of a record. Details in TWikiForms.
  • Template page, used as a template for new data records. It is essentially a TWiki page with a form attached to it. Details in TWikiTemplates.
  • Header page: Optional page included in each record page to summarize the record.
  • Page with an HTML form to create new records.
  • Report page(s). Details in VarSEARCH and FormattedSearch.

TWiki.org has a blog post on How to Create a TWiki Application where you can learn the details.

Back to: TWikiFAQ

Related Topics: UserDocumentationCategory

-- Contributors: TWiki:Main.MiyokoTakushima, TWiki:Main.PeterThoeny

Appendix B: Encode URLs With UTF8

Use internationalised characters within WikiWords and attachment names

This topic addresses implemented UTF-8 support for URLs only. The overall plan for UTF-8 support for TWiki is described in TWiki:Codev.ProposedUTF8SupportForI18N.

Current Status

To simplify use of internationalised characters within WikiWords and attachment names, TWiki now supports UTF-8 URLs, converting on-the-fly to virtually any character set, including ISO-8859-*, KOI8-R, EUC-JP, and so on.

Support for UTF-8 URL encoding avoids having to configure the browser to turn off this encoding in URLs (the default in Internet Explorer, Opera Browser and some Mozilla Browser URLs) and enables support of browsers where only this mode is supported (e.g. Opera Browser for Symbian smartphones). A non-UTF-8 site character set (e.g. ISO-8859-*) is still used within TWiki, and in fact pages are stored and viewed entirely in the site character set - the browser dynamically converts URLs from the site character set into UTF-8, and TWiki converts them back again.

System requirements are updated as follows:

  • ASCII or ISO-8859-1-only sites do not require any additional CPAN modules to be installed.
  • Perl 5.8 sites using any character set do not require additional modules, since CPAN:Encode is installed as part of Perl.
  • This feature still works on Perl 5.005_03 as per TWikiSystemRequirements, or Perl 5.6, as long as CPAN:Unicode::MapUTF8 is installed.

The following 'non-ASCII-safe' character encodings are now excluded from use as the site character set, since they interfere with TWiki markup: ISO-2022-*, HZ-*, Shift-JIS, MS-Kanji, GB2312, GBK, GB18030, Johab and UHC. However, many multi-byte character sets work fine, e.g. EUC-JP, EUC-KR, EUC-TW, and EUC-CN. In addition, UTF-8 can already be used, with some limitations, for East Asian languages where EUC character encodings are not acceptable - see TWiki:Codev.ProposedUTF8SupportForI18N.

It's now possible to override the site character set defined in the {SiteLocale} setting in configure - this enables you to have a slightly different spelling of the character set in the server locale (e.g. 'eucjp') and the HTTP header sent to the browser (e.g. 'euc-jp').

This feature should also support use of Mozilla Browser with TWiki:Codev.TWikiOnMainframe (as long as mainframe web server can convert or pass through UTF-8 URLs) - however, this specific combination is not tested. Other browser-server combinations should not have any problems.

Please note that use of UTF-8 as the site character set is not yet supported - see Phase 2 of TWiki:Codev.ProposedUTF8SupportForI18N for plans and work to date in this area.

This feature is complete in TWiki releases newer than February 2004.

Note for skin developers: is no longer required (TWiki:Plugins.InternationalisingYourSkin).

Details of Implementation

URLs are not allowed to contain non-ASCII (8th bit set) characters: http://www.w3.org/TR/html4/appendix/notes.html#non-ascii-chars

The overall plan for UTF-8 support for TWiki is described in two phases in TWiki:/Codev.ProposedUTF8SupportForI18N - this page addresses the first phase, in which UTF-8 is supported for URLs only.

UTF-8 URL translation to virtually any character set is supported as of TWiki Release 01 Sep 2004, but full UTF-8 support (e.g. pages in UTF-8) is not supported yet - this will be phase 2.

The code automatically detects whether a URL is UTF-8 or not, taking care to avoid over-long and illegal UTF-8 encodings that could introduce TWiki:Codev.MajorSecurityProblemWithIncludeFileProcessing (tested against a comprehensive UTF-8 test file, which IE 5.5 fails quite dangerously, and Opera Browser passes). Any non-ASCII URLs that are not valid UTF-8 are then assumed to be directly URL-encoded as a single-byte or multi-byte character set (as now), e.g. EUC-JP.

The main point is that you can use TWiki with international characters in WikiWords without changing your browser setup from the default, and you can also still use TWiki using non-UTF-8 URLs. This works on any Perl version from 5.005_03 onwards and corresponds to Phase 1 of TWiki:Codev.ProposedUTF8SupportForI18N. You can have different users using different URL formats transparently on the same server.

UTF-8 URLs are automatically converted to the current {Site}{Charset}, using modules such as CPAN:Encode if needed.

TWiki generates the whole page in the site charset, e.g. ISO-8859-1 or EUC-JP, but the browser dynamically UTF-8 encodes the attachment's URL when it's used. Since Apache serves attachment downloads without TWiki being involved, TWiki's code can't do its UTF-8 decoding trick, so TWiki URL-encodes such URLs in ISO-8859-1 or whatever when generating the page, to bypass this URL encoding, ensuring that the URLs and filenames seen by Apache remain in the site charset.

TWiki:Codev.TWikiOnMainframe uses EBCDIC web servers that typically translate their output to ASCII, UTF-8 or ISO-8859-1 (and URLs in the other direction) since there are so few EBCDIC web browsers. Such web servers don't work with even ISO-8859-1 URLs if they are URL encoded, since the automated translation is bypassed for URL-encoded characters. For TWiki on Mainframe, TWiki assumes that the web server will automatically translate UTF-8 URLs into EBCDIC URLs, as long as URL encoding is turned off in TWiki pages.

Testing and Limitation

It should work with TWiki:Codev.TWikiOnMainframe. Tested with IE 5.5, Opera 7.11 and Mozilla (Firebird 0.7).

Opera Browser on the P800 smartphone is working for page viewing but leads to corrupt page names when editing pages.

For up to date information see TWiki:Codev.EncodeURLsWithUTF8

Related Topics: AdminDocumentationCategory

TWiki Backup & Restore Console

Overview

NOTE: Only members of the TWikiAdminGroup can see the backup & restore console.

Related Topics: BackupRestorePlugin, AdminToolsCategory

Backup & Restore Plugin

%SHORTDESCRIPTION%

Overview

This is a solution to backup, restore, and upgrade TWiki sites. It can be used via the browser and on the command line. This plugin is pre-installed in TWiki-5.1 and later releases. It can be installed in older TWiki releases as oldas TWiki-2001-09-01 (Athens Release) to easily create a backup that can be restored on a new TWiki release. This offers an easy upgrade path for TWiki.

This plugin backs up page data, attachment data, the plugin workspace area, and the TWiki configuration. However, it does not backup the TWiki engine, additional plugins, and skins you might have installed. It is recommended to do a manual backup of the whole twiki directory after installing plugins and skins.

Web-based Operation

The backup and restore functionality is restricted to members of the TWikiAdminGroup.

Once configured, visit the BackupRestoreConsole to:

  • Start a new backup.
  • Cancel a backup in progress.
  • List all backups.
  • Delete a backup.
  • Restore from a backup.

Screenshot of Backup & Restore Console, overview:

Backup Console, Overview

How to Upgrade TWiki

The TWikiUpgradeGuide describes how to manually upgrade TWiki. It is much easier to use the BackupRestorePlugin to do a TWiki upgrade. Follow these steps:

  1. Install the BackupRestorePlugin on your old TWiki installation.
  2. Create a backup using the TWiki Backup & Restore Console (linked from plugin topic).
    • This creates a backup of name twiki-backup-2024-04-29-05-49.zip in the backup directory (default /tmp).
  3. Install the latest TWiki and additional plugins you need.
    • Install the latest BackupRestorePlugin.
  4. Transfer the backup zip file to the backup directory of the new TWiki installation (not needed if on same server).
    • The TWiki Backup & Restore Console overview should show the backup of the old TWiki.
  5. Use the TWiki Backup & Restore Console to restore the backup to the new TWiki.
    • Check the "Overwrite existing pages" checkbox.
    • Check the "Upgrade restored webs with latest system pages" checkbox.
    • Check the "Restore plugin work area" checkbox.

Screenshot of Backup & Restore Console, detail view of very old TWiki-01-Sep-2001 backup:

Backup Console, Detail

Command Line Utility and Cron

The backuprestore utility can be used to create a backup (scheduled or manually), to copy a backup, and to check on the status of the backup process.

Command Description
./backuprestore status Show backup status. Returns backup_status: 1 if web-based backup is in progress.
./backuprestore create_backup Create a backup. This is done without a background daemon process, e.g. the script returns when the backup is done.
./backuprestore download_backup <name.zip> Dump a backup file to STDOUT. If called as CGI script, download a backup file.

ALERT! Important Notes:

  • The utility must run as the same user as the CGI scripts executed by the webserver. This can be apache, nobody, www-data, wwwrun or the like, and depends on the webserver configuration.
  • Change to the twiki/bin directory before executing the backuprestore utility.

Scheduled backups can be done with a cron job. Example crontab entry that creates a backup at 10 minutes past midnight every Sunday:

10 0 * * 0 (cd /path/to/twiki/bin; ./backuprestore create_backup >/dev/null 2>&1)

Make sure the plugin is configured properly before creating backups. The backup destination can be local or remote. If remote, the remote server needs to be mounted on the TWiki server via NFS or the like.

Specification

  • Configuration:
    • {Plugins}{BackupRestorePlugin}{BackupDir} - Backup destination directory. Default: /tmp.
    • {Plugins}{BackupRestorePlugin}{KeepNumberOfBackups} - keep number of backups (e.g. delete old backups), 0 to keep all. Default: 7
    • {Plugins}{BackupRestorePlugin}{TempDir} - temp directory. Default: /tmp
    • {Plugins}{BackupRestorePlugin}{createZipCmd} - create zip command. Default: /usr/bin/zip -r
    • {Plugins}{BackupRestorePlugin}{listZipCmd} - list zip content command. Default: /usr/bin/unzip -l
    • {Plugins}{BackupRestorePlugin}{unZipCmd} - unzip command. Default: /usr/bin/unzip -o
    • {Plugins}{BackupRestorePlugin}{Debug} - debug flag. Default: 0
  • Backup files:
    • Location: Specified by the {Plugins}{BackupRestorePlugin}{BackupDir} configure setting.
    • Name: twiki-backup-2024-04-29-05-49.zip - date based names.
  • Backup format of .zip file:
    • data/* - all data and logs.
    • pub/* - all attachments.
    • working/* - working data.
    • working/BackupRestorePlugin/LocalSite.cfg - TWiki configuration file (if found).
    • working/BackupRestorePlugin/LocalLib.cfg - TWiki lib file (if found).
    • working/BackupRestorePlugin/twiki.conf - Apache config file (if found).
    • working/BackupRestorePlugin/version.txt - contains the TWiki version number of the backup. Used to intelligently restore backup to newer TWiki version. Example:
      version: TWiki-5.1.0
      short: 5.1
    • working/BackupRestorePlugin/version-long-TWiki-5.1.0.txt - file with TWiki version in filename
    • working/BackupRestorePlugin/version-short-5.1.txt - file with TWiki short-version in filename, name version-short-<major>.<minor>.txt

Syntax Rules

This section is only relevant to plugin developers. This plugin handles a %BACKUPRESTORE{"..."}% variable to perform all web-based operations. The variable is used in the BackupRestoreConsole page.

%BACKUPRESTORE{"..."}% parameters:

Parameter Explanation Default
action="..." Action to take:
"" (empty) - show backup overview console.
"backup_detail" - show backup detail console.
"create_backup" - start new backup.
"cancel_backup" - cancel backup in progress.
"delete_backup" - delete a backup.
"restore_backup" - restore from a backup.
"status" - show backup status (1: backup in progress).
"debug" - debug and diagnostics - {Plugins}{BackupRestorePlugin}{Debug} must be enabled.
"" (empty)
file="..." Name of backup file to take action. The file parameter is required for the following actions: "backup_detail", "delete_backup" and "restore_backup". ""

This plugin starts a daemon (background process) when a backup is started. Status is checked via Ajax calls. Once the new backup is finished it shows up in the backup table.

Limitations and To-Do

  • The zip utility on most platforms has a limitation of 4GB.
    • Fix: Install the latest zip 3.x and unzip 6.x utilities from infozip project on SourceForge.
    • Workaround: Follow the manual upgrade instructions at TWikiUpgradeGuide if you have more data.
  • A web-based backup is currently not supported on a native Windows installation of TWiki.
    • Workaround: Use command line utility on Windows.
  • Restore is currently not supported on a native Windows installation of TWiki.
    • Workaround: Follow the upgrade instructions at TWikiUpgradeGuide, section Copy your old webs to new TWiki.
  • Cancelling a backup or restore might leave some temporary files in the {Plugins}{BackupRestorePlugin}{BackupDir} directory.

  • To-do:
    • Option to backup engine (bin, lib, locale, templates, tools).
    • Option to restore log files.

  • Ideas for enhancements:
    • In backup, record $TWiki::cfg{Site}{CharSet} setting; on restore do a char-set re-encoding if needed (for example from ISO-8859-15 to UTF-8)
    • Unlock RCS files if restoring from old TWiki.
    • Add incremental backup and restore feature.

License and Bug Reporting

This plugin has been reasonably tested. If you find any issues please file a bug report at TWikibug:BackupRestorePlugin.

This plugin is distributed under GPL (GNU General Public License) in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

Plugin Installation & Configuration

This plugin is pre-installed from TWiki-5.1 on. TWiki administrators can upgrade the plugin as needed on the TWiki server.

  • For an automated installation, run the configure script and follow "Find More Extensions" in the in the Extensions section.

  • Or, follow these manual installation steps:
    • Download the ZIP file from the Plugins home (see below).
    • Unzip BackupRestorePlugin.zip in your twiki installation directory. Content:
      File: Description:
      bin/backuprestore CGI/command line utility
      data/TWiki/BackupRestorePlugin.txt Plugin topic
      data/TWiki/BackupRestoreConsole.txt Backup and restore console topic
      lib/TWiki/Plugins/BackupRestorePlugin.pm Plugin Perl module
      lib/TWiki/Plugins/BackupRestorePlugin/CaptureOutput.pm Perl module
      lib/TWiki/Plugins/BackupRestorePlugin/Core.pm Core backup module
      lib/TWiki/Plugins/BackupRestorePlugin/ProcDaemon.pm Perl module
    • Set the ownership of the extracted directories and files to the webserver user.

  • Plugin configuration and testing:
    • Run the configure script and enable the plugin in the Plugins section.
    • Configure additional BackupRestorePlugin settings in the Extensions section.
      Alternatively, add the following to twiki/lib/LocalSite.cfg and customize as needed:
        # Path to backup destination directory. Can be a volume mounted to the file system.
        $TWiki::cfg{Plugins}{BackupRestorePlugin}{BackupDir} = '/tmp';
        # Keep number of backups (e.g. delete old backups), 0 to keep all.
        $TWiki::cfg{Plugins}{BackupRestorePlugin}{KeepNumberOfBackups} = '7';
        # Path to temp directory, used by BackupRestorePlugin daemon for temporary data.
        $TWiki::cfg{Plugins}{BackupRestorePlugin}{TempDir} = '/tmp';
        # Path to zip command with options to recursively archive files and directory.
        $TWiki::cfg{Plugins}{BackupRestorePlugin}{createZipCmd} = '/usr/bin/zip -r';
        # Path to unzip command with options to list all files.
        $TWiki::cfg{Plugins}{BackupRestorePlugin}{listZipCmd} = '/usr/bin/unzip -l';
        # Path to unzip command with options to unzip all files with option to overwrite existing files.
        $TWiki::cfg{Plugins}{BackupRestorePlugin}{unZipCmd} = '/usr/bin/unzip -o';
        # Debug plugin. See output in data/debug.txt
        $TWiki::cfg{Plugins}{BackupRestorePlugin}{Debug} = 0;
    • If your TWiki is older than TWiki-4.0, create a twiki/lib/LocalSite.cfg file with above $TWiki::cfg settings and end the file with: 1;
    • If your TWiki is an old TWiki-2001-09-01 (Athens Release), create a twiki/bin/setlib.cfg file with this content:
        my $twikiLibPath = "/path/to/your/twiki/lib";
        unshift @INC, $twikiLibPath;
        1;
    • If your TWiki is older than TWiki-4.2, create a working directory in the twiki root (same level as twiki/lib), and set ownership to the webserver user.
    • Test if the installation was successful: See BackupRestoreConsole.

Plugin Info

  • One line description, is shown in the TextFormattingRules topic:
    • Set SHORTDESCRIPTION = Administrator utility to backup, restore and upgrade a TWiki site

Plugin Author: TWiki:Main.PeterThoeny, TWiki.org
Copyright: © 2011-2021 TWiki:Main.PeterThoeny
© 2011-2021 TWiki:TWiki.TWikiContributor
© 2004, 2005 Simon Flack (for CPAN:IO::CaptureOutput)
© 2007, 2008 David Golden (for CPAN:IO::CaptureOutput)
© 1997-2011 by Earl Hood and Detlef Pilzecker (for CPAN:Proc::Daemon)
License: GPL (GNU General Public License)
Plugin Version: 2021-03-19
2021-03-19: TWikibug:Item7927: Copyright update to 2021
2018-07-10: TWikibug:Item7841: Copyright update to 2018
2017-12-31: TWikibug:Item7831: Allow action=debug only if Debug flag set; parameter sanity checks
2016-01-08: TWikibug:Item7708: Copyright update to 2016
2015-01-09: TWikibug:Item7604: Switch to GPL v3
2013-02-16: TWikibug:Item7091: Use TWISTY in installation instructions section and change history
2012-09-03: TWikibug:Item6837: Doc update with zip utility limitation of 4GB
2012-01-13: TWikibug:Item6796: Fixing copyright year to 2012
2011-12-19: TWikibug:Item6799: Improved docs on GNU zip dependency
2011-09-13: TWikibug:Item6796: Improved docs on command line use
2011-09-05: TWikibug:Item6795: Add restore from backup functionality; upgrade old system topics on restore of old TWiki; describe how to upgrade TWiki
2011-08-17: TWikibug:Item6793: Avoid or work around newer APIs to make plugin run on old TWiki-2001-09-01 (Athens Release) for backup
2011-08-16: TWikibug:Item6793: Add screenshot; add Config.spec configure file; proper detection of command line mode also for older TWiki versions; use TWiki::Func::registerTagHandler only if available so that plugin can run in older TWiki versions
2011-08-15: TWikibug:Item6793: Better error handling; add magic number to download URL to restrict download of backups to TWiki admins only
2011-08-12: TWikibug:Item6631: Initial version
TWiki Dependency: $TWiki::Plugins::VERSION 1.0
CPAN Dependencies: none
(Proc::Daemon included as TWiki::Plugins::BackupRestorePlugin::ProcDaemon)
(IO::CaptureOutput included as TWiki::Plugins::BackupRestorePlugin::CaptureOutput )
Other Dependencies: GNU zip and unzip command line utilities
Perl Version: 5.005
TWiki:Plugins.Benchmark: GoodStyle nn%, FormattedSearch nn%, BackupRestorePlugin nn%
Plugin Home: http://TWiki.org/cgi-bin/view/Plugins/BackupRestorePlugin
Feedback: http://TWiki.org/cgi-bin/view/Plugins/BackupRestorePluginDev
Appraisal: http://TWiki.org/cgi-bin/view/Plugins/BackupRestorePluginAppraisal

Related Topics: BackupRestoreConsole, TWikiPreferences, TWikiPlugins, AdminToolsCategory

Behaviour Javascript Framework Contrib

%SHORTDESCRIPTION%

Introduction

This contrib packages the third-party Behaviour Javascript event library, available from http://bennolan.com/behaviour/.

Behaviour uses CSS selectors to subscribe to Javascript event handlers. This allows to create clean code, separated from HTML (and well suited to create Javascript based interaction that degrades nicely when Javascript is not available).

From the website:

After all the work of WASP and others to promote clean markup, valid pages and graceful degradation via css - it sucks that we're going back to tag soup days by throwing javascript tags into our html.

The better way to do javascript is to do it unobtrusively. PPK and Simon Willison have been recommending this approach for ages. And it's definitely the way to go. The only problem is that it's a bit of a pain in the ass.

That's why I came up with Behaviour - my solution to unobtrusive javascript behaviours.

How does it work?

Behaviour lets you use CSS selectors to specify elements to add javascript events to. This means that instead of writing:

<li>
 <a onclick="this.parentNode.removeChild(this)" href="#">
  Click me to delete me
 </a>
</li>

You can use:

<ul id="example">
 <li>
  <a href="/someurl">Click me to delete me</a>
 </li>
</ul>

And then use css selectors to select that element and add javascript functions to it.

var myrules = {
 '#example li' : function(el){
  el.onclick = function(){
   this.parentNode.removeChild(this);
  }
 }
};
Behaviour.register(myrules);

Usage

Include the Javascript file:

<script type="text/javascript" src="%PUBURL%/%SYSTEMWEB%/BehaviourContrib/behaviour.js"></script>

In your code you create a "rules" object, with sub-objects for each html element class name or id:

var myrules = {
 '.classname' : function(element) {
  // element event
  element.onclick = function() {
   // code here
  }
 },
 '#id' : function(element) {
  // element event
  element.onclick = function() {
   // code here
  }
 }
};

Or use nested identifiers:

var myrules = {
 '.menu li a' : function(element) {
  element.onclick = function() {
   // code here
  }
 }
};

Apply the rules with:

Behaviour.register(myrules);

Example

If we have a 'normal' link to TWiki Web hometopic: TWiki Web Home, we can use javascript to make it open a popup window. When javascript is not available the link behaviour defaults to opening the page in the current window.

<div id="demoblock" style="padding:1em; width:100px; text-align:center;">
MOUSE OVER ME
</div>

<script type="text/javascript">
// <![CDATA[
var myrules = {
 '#demoblock' : function(el) {
  var defaultColor = '#A3D6F8';
  var highlightColor = '#4A7FB5';

  el.style.backgroundColor = defaultColor;

  el.onmouseover = function() {
   this.style.backgroundColor = highlightColor;
   return false;
  }
  el.onmouseout = function() {
   this.style.backgroundColor = defaultColor;
   return false;
  }
 },
 '#demoblock span' : function(el) {

  var text = el.innerHTML;

  var fisherYates = function (inArray) {
   var i = inArray.length;
   if ( i == 0 ) return false;
   while ( --i ) {
    var j = Math.floor( Math.random() * ( i + 1 ) );
    var tempi = inArray[i];
    var tempj = inArray[j];
    inArray[i] = tempj;
    inArray[j] = tempi;
   }
  }

  var randomize = function(inText) {
   var letters = inText.split('');
   fisherYates(letters);
   return letters.join('');
  }
  el.onmouseover = function() {
   this.innerHTML = randomize(text);
   return false;
  }
  el.onmouseout = function() {
   this.innerHTML = text;
   return false;
  }
 }
};
Behaviour.register(myrules);
// ]]>
</script>

Creates:

MOUSE OVER ME

Leaking Danger

Behaviour code leaks memory on Windows Explorer prior to version 7. To prevent leaking, set the element variable to null:

var myrules = {
 'table.test td' : function(element) {
  element.onmouseover = function() {
   this.style.backgroundColor = highlightColor;
   return false;
  }
  element = null; // by setting this IE will not leak  
 }
};   
Behaviour.register(myrules);

Development

License

Behaviour is freely distributable under the terms of an BSD license. For details see the Behaviour website.

Links

Installation Instructions

You do not need to install anything in the browser to use this extension. The following instructions are for the administrator who installs the extension on the server where TWiki is running.

Like many other TWiki extensions, this module is shipped with a fully automatic installer script written using the BuildContrib.

  • If you have TWiki 4.2 or later, you can install from the configure interface (Go to Plugins->Find More Extensions)
  • If you have any problems, then you can still install manually from the command-line:
    1. Download one of the .zip or .tgz archives
    2. Unpack the archive in the root directory of your TWiki installation.
    3. Run the installer script ( perl <module>_installer )
    4. Run configure and enable the module, if it is a plugin.
    5. Repeat for any missing dependencies.
  • If you are still having problems, then instead of running the installer script:
    1. Make sure that the file permissions allow the webserver user to access all files.
    2. Check in any installed files that have existing ,v files in your existing install (take care not to lock the files when you check in)
    3. Manually edit LocalSite.cfg to set any configuration variables.

Contrib Settings

  • Set SHORTDESCRIPTION = Behaviour Javascript event library to create Javascript based interactions that degrade well when Javascript is not available

You can also set the global TWiki variable BEHAVIOURCONTRIB_DEBUG to 1 to make the contrib use uncompressed javascript sources, in the event of problems.

Contrib Info

Author: TWiki:Main/ArthurClemens
Copyright: Code: behaviour.js version 1.1 - Copyright (c) Ben Nolan and Simon Willison.
TWiki distribution and updates/additions: © TWiki:Main/ArthurClemens.
© 2006-2010 TWiki:TWiki/TWikiContributor
License: BSD for behaviour.js
GPL (GNU General Public License) for TWiki BehaviourContrib
Version: 18694 (2010-05-29)
Dependencies: None
Contrib Version: 1.4
Change History:  
2010-05-15: TWikibug:Item6433 - doc improvements; replacing TWIKIWEB with SYSTEMWEB
17 Oct 2007 1.3 Replaced "faster code" by other code from Dean Edwards, [[ packed by http://groups.google.com/group/behaviour/browse_thread/thread/85137977bedf5ed/3cf3ba8065d41a8c#3cf3ba8065d41a8c][Raymond Irving]].
02 Jul 2007 1.2 Integrated other faster code by Dean Edwards: faster onload (again).
08 Mar 2007 1.1 Integrated code by Dean Edwards (see Code update version 1.1 with faster DOM queries).
04 Jun 2006 1.0 First Version. Included Behaviour version: 1.1.
Home: http://TWiki.org/cgi-bin/view/Plugins/BehaviourContrib
Feedback: http://TWiki.org/cgi-bin/view/Plugins/BehaviourContribDev
Appraisal: http://TWiki.org/cgi-bin/view/Plugins/BehaviourContribAppraisal

Related Topics: TWikiPreferences

Book View

BookView is an option available from the advanced search topic. It allows you to display the result in "book view", that is, the whole content of topics is shown instead of a topic summary. This allows you to easily see a whole set of pages.

If you want to print a set of pages it is recommended to create a topic that includes a set of topics, which gives more control over formatting and layout for printing.

Related Topics: UserDocumentationCategory, WebSearchAdvanced

-- Contributors: TWiki:Main/PeterThoeny, TWiki:Main/MattWilkie

Bulk Registration

Administrators can use this topic to register (i.e. create logins and user topics) for a group of people in one batch.

Unlike normal registration the administrator is assumed to have correct e-mail addresses for the users, so no verification is required. Note that the new users are not notified that they have an account. This is so you can prepare and verify the accounts before announcing them. To announce them use the BulkResetPassword feature: this will assign a new random password and notify users.

Bulk Registration usage

Note: this is an administrator job - only admistrators can run this.

If you are administrator, you will take these actions:

  1. (First time use) Create new bulk registration topics (see Settings below).
  2. In the REGISTERTOPIC topic: create a table of new users. An example table is provided below to copy.
  3. Return to this topic and press the button "Bulk Register" to create the new topics.
  4. Read %LOGTOPIC% to verify if all has gone well.
  5. When you are ready, use the BulkResetPassword page to assign passwords and notify the users of their new accounts.

Below are the details.

Settings

  • Define where to pick up the table of users to register
  • Use this to define where to log the bulk registration process. It needs to be a topic name in this web.
    • Set LOGTOPIC = %REGISTERTOPIC%Log
  • Set this to 1 to make the bulk registration overwrite any existing user topics. By default, existing user topics are left alone.
    • Set OVERWRITEHOMETOPICS = 0

The user table

This table is a template for user data that will be written to the new user topics. If you stick to these basic fields you can just use the first example below. If you want to write more data (like phone number or country) read the section Customizing user data as well.

Example format

The following should be inserted into your %REGISTERTOPIC% as a table. This is the most simple format:
<noautolink>
%EDITTABLE{}%
| FirstName | LastName | Email | WikiName |
| Test | User | you@example.com | TestUser |
</noautolink>

Usage:

  1. Copy this text to your clipboard
  2. Click through and paste this on %REGISTERTOPIC%.
  3. Add and customize entries, save table. Note that the first row must not contain bolded entries, so don't apply any formatting.
  4. Return here

Customizing user data

You can write additional data to the new user topics. Do this by enhancing the user table with additional field names as table headers.

Any fields you define in this table will end up in the User's topic. If a form (such as UserForm) is attached to NewUserTemplate then the data will go in as META:FIELDS, meaning that you can use SEARCH formfield constructs to search.

If you use the UserForm then ensure that it contains all the fields you define here. Otherwise they will disappear when the user edits their home topic!

Mandatory fields

  • WikiName
  • FirstName
  • LastName

Optional fields

Customized table example

Make sure that the extra fields also appear on the UserForm.
<noautolink>
%EDITTABLE{}%
| FirstName | LastName | Email | WikiName | CustomFieldThis | SomeOtherRandomField | WhateverYouLike |
| Test | User | you@example.com | TestUser | A | B | C |
</noautolink>


 

%REGISTERTOPIC%

%LOGTOPIC%

Related Topics: AdminToolsCategory

Package =

extends CGI::Session::ErrorHandler

=head1 NAME

CGI::Session - persistent session data in CGI applications

=head1 SYNOPSIS

# Object initialization: use CGI::Session; $session = new CGI::Session();

$CGISESSID = $session->id();

# send proper HTTP header with cookies: print $session->header();

# storing data in the session $session->param('f_name', 'Sherzod'); # or $session->param(-name=>'l_name', -value=>'Ruzmetov');

# flush the data from memory to the storage driver at least before your # program finishes since auto-flushing can be unreliable $session->flush();

# retrieving data my $f_name = $session->param('f_name'); # or my $l_name = $session->param(-name=>'l_name');

# clearing a certain session parameter $session->clear(["l_name", "f_name"]);

# expire '_is_logged_in' flag after 10 idle minutes: $session->expire('is_logged_in', '+10m')

# expire the session itself after 1 idle hour $session->expire('+1h');

# delete the session for good $session->delete();

=head1 DESCRIPTION

CGI-Session is a Perl5 library that provides an easy, reliable and modular session management system across HTTP requests. Persistency is a key feature for such applications as shopping carts, login/authentication routines, and application that need to carry data across HTTP requests. CGI::Session does that and many more.

=head1 TRANSLATIONS

This document is also available in Japanese.

=over 4

=item o

Translation based on 4.14: http://digit.que.ne.jp/work/index.cgi?Perldoc/ja

=item o

Translation based on 3.11, including Cookbook and Tutorial: http://perldoc.jp/docs/modules/CGI-Session-3.11/

=back

=head1 TO LEARN MORE

Current manual is optimized to be used as a quick reference. To learn more both about the philosophy and CGI::Session programming style, consider the following:

=over 4

=item *

L<CGI::Session::Tutorial|CGI::Session::Tutorial> - extended CGI::Session manual. Also includes library architecture and driver specifications.

=item *

We also provide mailing lists for CGI::Session users. To subscribe to the list or browse the archives visit https://lists.sourceforge.net/lists/listinfo/cgi-session-user

=item *

B - "HTTP State Management Mechanism" found at ftp://ftp.isi.edu/in-notes/rfc2965.txt

=item *

L<CGI|CGI> - standard CGI library

=item *

L<Apache::Session|Apache::Session> - another fine alternative to CGI::Session.

=back

=head1 METHODS

Following is the overview of all the available methods accessible via CGI::Session object.

=head2 new()

=head2 new( $sid )

=head2 new( $query )

=head2 new( $dsn, $query||$sid )

=head2 new( $dsn, $query||$sid, \%dsn_args )

Constructor. Returns new session object, or undef on failure. Error message is accessible through L<errstr() - class method|CGI::Session::ErrorHandler/errstr>. If called on an already initialized session will re-initialize the session based on already configured object. This is only useful after a call to L<load()|/"load">.

Can accept up to three arguments, $dsn - Data Source Name, $query||$sid - query object OR a string representing session id, and finally, \%dsn_args, arguments used by $dsn components.

If called without any arguments, $dsn defaults to I<driver:file;serializer:default;id:md5>, $query||$sid defaults to C<< CGI->new() >>, and C<\%dsn_args> defaults to I.

If called with a single argument, it will be treated either as C<$query> object, or C<$sid>, depending on its type. If argument is a string , C<new()> will treat it as session id and will attempt to retrieve the session from data store. If it fails, will create a new session id, which will be accessible through L<id() method|/"id">. If argument is an object, L<cookie()|CGI/cookie> and L<param()|CGI/param> methods will be called on that object to recover a potential C<$sid> and retrieve it from data store. If it fails, C<new()> will create a new session id, which will be accessible through L<id() method|/"id">. C<name()> will define the name of the query parameter and/or cookie name to be requested, defaults to I.

If called with two arguments first will be treated as $dsn, and second will be treated as $query or $sid or undef, depending on its type. Some examples of this syntax are:

$s = CGI::Session->new("driver:mysql", undef); $s = CGI::Session->new("driver:sqlite", $sid); $s = CGI::Session->new("driver:db_file", $query); $s = CGI::Session->new("serializer:storable;id:incr", $sid); # etc...

Following data source components are supported:

=over 4

=item *

B - CGI::Session driver. Available drivers are L<file|CGI::Session::Driver::file>, L<db_file|CGI::Session::Driver::db_file>, L<mysql|CGI::Session::Driver::mysql> and L<sqlite|CGI::Session::Driver::sqlite>. Third party drivers are welcome. For driver specs consider L<CGI::Session::Driver|CGI::Session::Driver>

=item *

B - serializer to be used to encode the data structure before saving in the disk. Available serializers are L<storable|CGI::Session::Serialize::storable>, L<freezethaw|CGI::Session::Serialize::freezethaw> and L<default|CGI::Session::Serialize::default>. Default serializer will use L<Data::Dumper|Data::Dumper>.

=item *

B - ID generator to use when new session is to be created. Available ID generator is L<md5|CGI::Session::ID::md5>

=back

For example, to get CGI::Session store its data using DB_File and serialize data using FreezeThaw:

$s = new CGI::Session("driver:DB_File;serializer:FreezeThaw", undef);

If called with three arguments, first two will be treated as in the previous example, and third argument will be C<\%dsn_args>, which will be passed to C<$dsn> components (namely, driver, serializer and id generators) for initialization purposes. Since all the $dsn components must initialize to some default value, this third argument should not be required for most drivers to operate properly.

undef is acceptable as a valid placeholder to any of the above arguments, which will force default behavior.

=head2 load()

=head2 load($query||$sid)

=head2 load($dsn, $query||$sid)

=head2 load($dsn, $query, \%dsn_args);

Accepts the same arguments as new(), and also returns a new session object, or undef on failure. The difference is, L<new()|/"new"> can create new session if it detects expired and non-existing sessions, but C<load()> does not.

C<load()> is useful to detect expired or non-existing sessions without forcing the library to create new sessions. So now you can do something like this:

$s = CGI::Session->load() or die CGI::Session->errstr(); if ( $s->is_expired ) { print $s->header(), $cgi->start_html(), $cgi->p("Your session timed out! Refresh the screen to start new session!") $cgi->end_html(); exit(0); }

if ( $s->is_empty ) { $s = $s->new() or die $s->errstr; }

Notice, all I sessions are empty, but not all I sessions are expired!

=head2 id()

Returns effective ID for a session. Since effective ID and claimed ID can differ, valid session id should always be retrieved using this method.

=head2 param($name)

=head2 param(-name=E$name)

Used in either of the above syntax returns a session parameter set to $name or undef if it doesn't exist. If it's called on a deleted method param() will issue a warning but return value is not defined.

=head2 param($name, $value)

=head2 param(-name=E$name, -value=E$value)

Used in either of the above syntax assigns a new value to $name parameter, which can later be retrieved with previously introduced param() syntax. C<$value> may be a scalar, arrayref or hashref.

Attempts to set parameter names that start with I<_SESSION_> will trigger a warning and undef will be returned.

=head2 param_hashref()

B. Use L<dataref()|/"dataref"> instead.

=head2 dataref()

Returns reference to session's data table:

$params = $s->dataref(); $sid = $params->{_SESSION_ID}; $name= $params->{name}; # etc...

Useful for having all session data in a hashref, but too risky to update.

=head2 save_param()

=head2 save_param($query)

=head2 save_param($query, \@list)

Saves query parameters to session object. In other words, it's the same as calling L<param($name, $value)|/"param"> for every single query parameter returned by C<< $query->param() >>. The first argument, if present, should be either CGI object or any object which can provide param() method. If it's undef, defaults to the return value of L<query()|/"query">, which returns C<< CGI->new >>. If second argument is present and is a reference to an array, only those query parameters found in the array will be stored in the session. undef is a valid placeholder for any argument to force default behavior.

=head2 load_param()

=head2 load_param($query)

=head2 load_param($query, \@list)

Loads session parameters into a query object. The first argument, if present, should be query object, or any other object which can provide param() method. If second argument is present and is a reference to an array, only parameters found in that array will be loaded to the query object.

=head2 clear()

=head2 clear('field')

=head2 clear(\@list)

Clears parameters from the session object.

With no parameters, all fields are cleared. If passed a single parameter or a reference to an array, only the named parameters are cleared.

=head2 flush()

Synchronizes data in memory with the copy serialized by the driver. Call flush() if you need to access the session from outside the current session object. You should at least call flush() before your program exits.

As a last resort, CGI::Session will automatically call flush for you just before the program terminates or session object goes out of scope. This automatic behavior was the recommended behavior until the 4.x series. Automatic flushing has since proven to be unreliable, and in some cases is now required in places that worked with 3.x. For further details see:

http://rt.cpan.org/Ticket/Display.html?id=17541 http://rt.cpan.org/Ticket/Display.html?id=17299

=head2 atime()

Read-only method. Returns the last access time of the session in seconds from epoch. This time is used internally while auto-expiring sessions and/or session parameters.

=head2 ctime()

Read-only method. Returns the time when the session was first created in seconds from epoch.

=head2 expire()

=head2 expire($time)

=head2 expire($param, $time)

Sets expiration interval relative to L<atime()|/"atime">.

If used with no arguments, returns the expiration interval if it was ever set. If no expiration was ever set, returns undef. For backwards compatibility, a method named C<etime()> does the same thing.

Second form sets an expiration time. This value is checked when previously stored session is asked to be retrieved, and if its expiration interval has passed, it will be expunged from the disk immediately. Passing 0 cancels expiration.

By using the third syntax you can set the expiration interval for a particular session parameter, say I<~logged-in>. This would cause the library call clear() on the parameter when its time is up. Note it only makes sense to set this value to something I than when the whole session expires. Passing 0 cancels expiration.

All the time values should be given in the form of seconds. Following keywords are also supported for your convenience:

+-----------+---------------+

alias meaning
+-----------+---------------+
s Second
m Minute
h Hour
d Day
w Week
M Month
y Year
+-----------+---------------+

Examples:

$session->expire("2h"); # expires in two hours $session->expire(0); # cancel expiration $session->expire("~logged-in", "10m"); # expires '~logged-in' parameter after 10 idle minutes

Note: all the expiration times are relative to session's last access time, not to its creation time. To expire a session immediately, call L<delete()|/"delete">. To expire a specific session parameter immediately, call L<clear([$name])|/"clear">.

=head2 is_new()

Returns true only for a brand new session.

=head2 is_expired()

Tests whether session initialized using L<load()|/"load"> is to be expired. This method works only on sessions initialized with load():

$s = CGI::Session->load() or die CGI::Session->errstr; if ( $s->is_expired ) { die "Your session expired. Please refresh"; } if ( $s->is_empty ) { $s = $s->new() or die $s->errstr; }

=head2 is_empty()

Returns true for sessions that are empty. It's preferred way of testing whether requested session was loaded successfully or not:

$s = CGI::Session->load($sid); if ( $s->is_empty ) { $s = $s->new(); }

Actually, the above code is nothing but waste. The same effect could've been achieved by saying:

$s = CGI::Session->new( $sid );

L<is_empty()|/"is_empty"> is useful only if you wanted to catch requests for expired sessions, and create new session afterwards. See L<is_expired()|/"is_expired"> for an example.

=head2 delete()

Deletes a session from the data store and empties session data from memory, completely, so subsequent read/write requests on the same object will fail. Technically speaking, it will only set object's status to I and will trigger L<flush()|/"flush">, and flush() will do the actual removal.

=head2 find( \&code )

=head2 find( $dsn, \&code )

=head2 find( $dsn, \&code, \%dsn_args )

Experimental feature. Executes \&code for every session object stored in disk, passing initialized CGI::Session object as the first argument of \&code. Useful for housekeeping purposes, such as for removing expired sessions. Following line, for instance, will remove sessions already expired, but are still in disk:

The following line, for instance, will remove sessions already expired, but which are still on disk:

CGI::Session->find( sub {} );

Notice, above \&code didn't have to do anything, because load(), which is called to initialize sessions inside find(), will automatically remove expired sessions. Following example will remove all the objects that are 10+ days old:

CGI::Session->find( \&purge ); sub purge { my ($session) = @_; next if $session->is_empty; # <-- already expired?! if ( ($session->ctime + 3600*240) <= time() ) { $session->delete() or warn "couldn't remove " . $session->id . ": " . $session->errstr; } }

B: find will not change the modification or access times on the sessions it returns.

Explanation of the 3 parameters to C<find()>:

=over 4

=item $dsn

This is the DSN (Data Source Name) used by CGI::Session to control what type of sessions you previously created and what type of sessions you now wish method C<find()> to pass to your callback.

The default value is defined above, in the docs for method C<new()>, and is 'driver:file;serializer:default;id:md5'.

Do not confuse this DSN with the DSN arguments mentioned just below, under \%dsn_args.

=item \&code

This is the callback provided by you (i.e. the caller of method C<find()>) which is called by CGI::Session once for each session found by method C<find()> which matches the given $dsn.

There is no default value for this coderef.

When your callback is actually called, the only parameter is a session. If you want to call a subroutine you already have with more parameters, you can achieve this by creating an anonymous subroutine that calls your subroutine with the parameters you want. For example:

CGI::Session->find($dsn, sub { my_subroutine( @_, 'param 1', 'param 2' ) } ); CGI::Session->find($dsn, sub { $coderef->( @_, $extra_arg ) } );

Or if you wish, you can define a sub generator as such:

sub coderef_with_args { my ( $coderef, @params ) = @_; return sub { $coderef->( @_, @params ) }; }

CGI::Session->find($dsn, coderef_with_args( $coderef, 'param 1', 'param 2' ) );

=item \%dsn_args

If your $dsn uses file-based storage, then this hashref might contain keys such as:

{ Directory => Value 1, NoFlock => Value 2, UMask => Value 3 }

If your $dsn uses db-based storage, then this hashref contains (up to) 3 keys, and looks like:

{ DataSource => Value 1, User => Value 2, Password => Value 3 }

These 3 form the DSN, username and password used by DBI to control access to your database server, and hence are only relevant when using db-based sessions.

The default value of this hashref is undef.

=back

B<Note:> find() is meant to be convenient, not necessarily efficient. It's best suited in cron scripts.

=head1 MISCELLANEOUS METHODS

=head2 remote_addr()

Returns the remote address of the user who created the session for the first time. Returns undef if variable REMOTE_ADDR wasn't present in the environment when the session was created.

=head2 errstr()

Class method. Returns last error message from the library.

=head2 dump()

Returns a dump of the session object. Useful for debugging purposes only.

=head2 header()

Replacement for L<CGI.pm|CGI>'s header() method. Without this method, you usually need to create a CGI::Cookie object and send it as part of the HTTP header:

$cookie = CGI::Cookie->new(-name=>$session->name, -value=>$session->id); print $cgi->header(-cookie=>$cookie);

You can minimize the above into:

print $session->header();

It will retrieve the name of the session cookie from C<$session->name()> which defaults to C<$CGI::Session::NAME>. If you want to use a different name for your session cookie, do something like following before creating session object:

CGI::Session->name("MY_SID"); $session = new CGI::Session(undef, $cgi, \%attrs);

Now, $session->header() uses "MY_SID" as a name for the session cookie.

=head2 query()

Returns query object associated with current session object. Default query object class is L<CGI.pm|CGI>.

=head2 DEPRECATED METHODS

These methods exist solely for for compatibility with CGI::Session 3.x.

=head3 close()

Closes the session. Using flush() is recommended instead, since that's exactly what a call to close() does now.

=head1 DISTRIBUTION

CGI::Session consists of several components such as L<drivers|"DRIVERS">, L<serializers|"SERIALIZERS"> and L. This section lists what is available.

=head2 DRIVERS

Following drivers are included in the standard distribution:

=over 4

=item *

L<file|CGI::Session::Driver::file> - default driver for storing session data in plain files. Full name: B<CGI::Session::Driver::file>

=item *

L<db_file|CGI::Session::Driver::db_file> - for storing session data in BerkelyDB. Requires: L. Full name: B<CGI::Session::Driver::db_file>

=item *

L<mysql|CGI::Session::Driver::mysql> - for storing session data in MySQL tables. Requires L<DBI|DBI> and L<DBD::mysql|DBD::mysql>. Full name: B<CGI::Session::Driver::mysql>

=item *

L<sqlite|CGI::Session::Driver::sqlite> - for storing session data in SQLite. Requires L<DBI|DBI> and L<DBD::SQLite|DBD::SQLite>. Full name: B<CGI::Session::Driver::sqlite>

=back

=head2 SERIALIZERS

=over 4

=item *

L<default|CGI::Session::Serialize::default> - default data serializer. Uses standard L<Data::Dumper|Data::Dumper>. Full name: B<CGI::Session::Serialize::default>.

=item *

L<storable|CGI::Session::Serialize::storable> - serializes data using L. Requires L. Full name: B<CGI::Session::Serialize::storable>.

=item *

L<freezethaw|CGI::Session::Serialize::freezethaw> - serializes data using L. Requires L. Full name: B<CGI::Session::Serialize::freezethaw>

=item *

L<yaml|CGI::Session::Serialize::yaml> - serializes data using YAML. Requires L or L<YAML::Syck>. Full name: B<CGI::Session::Serialize::yaml>

=item *

L<json|CGI::Session::Serialize::json> - serializes data using JSON. Requires L<JSON::Syck>. Full name: B<CGI::Session::Serialize::json>

=back

=head2 ID GENERATORS

Following ID generators are available:

=over 4

=item *

L<md5|CGI::Session::ID::md5> - generates 32 character long hexadecimal string. Requires L<Digest::MD5|Digest::MD5>. Full name: B<CGI::Session::ID::md5>.

=item *

L<incr|CGI::Session::ID::incr> - generates incremental session ids.

=item *

L<static|CGI::Session::ID::static> - generates static session ids. B<CGI::Session::ID::static>

=back

=head1 CREDITS

CGI::Session evolved to what it is today with the help of following developers. The list doesn't follow any strict order, but somewhat chronological. Specifics can be found in F file

=over 4

=item Andy Lester

=item Brian King Emrbbking@mac.comE

=item Olivier Dragon Edragon@shadnet.shad.caE

=item Adam Jacob Eadam@sysadminsith.orgE

=item Igor Plisco Eigor@plisco.ruE

=item Mark Stosberg

=item Matt LeBlanc Emleblanc@cpan.orgE

=item Shawn Sorichetti

=back

=head1 COPYRIGHT

Copyright (C) 2001-2005 Sherzod Ruzmetov Esherzodr@cpan.orgE. All rights reserved. This library is free software. You can modify and or distribute it under the same terms as Perl itself.

=head1 PUBLIC CODE REPOSITORY

You can see what the developers have been up to since the last release by checking out the code repository. You can browse the Subversion repository from here:

http://svn.cromedome.net/

Or check it directly with C from here:

svn://svn.cromedome.net/CGI-Session

=head1 SUPPORT

If you need help using CGI::Session consider the mailing list. You can ask the list by sending your questions to cgi-session-user@lists.sourceforge.net .

You can subscribe to the mailing list at https://lists.sourceforge.net/lists/listinfo/cgi-session-user .

Bug reports can be submitted at http://rt.cpan.org/NoAuth/ReportBug.html?Queue=CGI-Session

=head1 AUTHOR

Sherzod Ruzmetov Esherzodr@cpan.orgE, http://author.handalak.com/

Mark Stosberg became a co-maintainer during the development of 4.0. C<markstos@cpan.org>.

=head1 SEE ALSO

=over 4

=item *

L<CGI::Session::Tutorial|CGI::Session::Tutorial> - extended CGI::Session manual

=item *

B - "HTTP State Management Mechanism" found at ftp://ftp.isi.edu/in-notes/rfc2965.txt

=item *

L<CGI|CGI> - standard CGI library

=item *

L<Apache::Session|Apache::Session> - another fine alternative to CGI::Session

=back

Package =

=head1 NAME

CGI::Session::Driver::DBI - Base class for native DBI-related CGI::Session drivers

=head1 SYNOPSIS

require CGI::Session::Driver::DBI; @ISA = qw( CGI::Session::Driver::DBI );

=head1 DESCRIPTION

In most cases you can create a new DBI-driven CGI::Session driver by simply creating an empty driver file that inherits from CGI::Session::Driver::DBI. That's exactly what L<sqlite|CGI::Session::Driver::sqlite> does. The only reason why this class doesn't suit for a valid driver is its name isn't in lowercase. I'm serious!

=head2 NOTES

CGI::Session::Driver::DBI defines init() method, which makes DBI handle available for drivers in I - object attribute regardless of what C<\%dsn_args> were used in creating session object. Should your driver require non-standard initialization you have to re-define init() method in your F<.pm> file, but make sure to set 'Handle' - object attribute to database handle (returned by DBI->connect(...)) if you wish to inherit any of the methods from CGI::Session::Driver::DBI.

=head1 STORAGE

Before you can use any DBI-based session drivers you need to make sure compatible database table is created for CGI::Session to work with. Following command will produce minimal requirements in most SQL databases:

CREATE TABLE sessions ( id CHAR(32) NOT NULL PRIMARY KEY, a_session TEXT NOT NULL );

Your session table can define additional columns, but the above two are required. Name of the session table is expected to be I by default. You may use a different name if you wish. To do this you have to pass I as part of your C< \%dsn_args >:

$s = new CGI::Session("driver:sqlite", undef, {TableName=>'my_sessions'}); $s = new CGI::Session("driver:mysql", undef, { TableName=>'my_sessions', DataSource=>'dbi:mysql:shopping_cart'});

=head1 DRIVER ARGUMENTS

Following driver arguments are supported:

=over 4

=item DataSource

First argument to be passed to L<DBI|DBI>->L<connect()|DBI/connect()>. If the driver makes the database connection itself, it will also explicitly disconnect from the database when the driver object is DESTROYed.

=item User

User privileged to connect to the database defined in C.

=item Password

Password of the I privileged to connect to the database defined in C

=item Handle

An existing L database handle object. The handle can be created on demand by providing a code reference as a argument, such as C<<sub{DBI->connect}>>. This way, the database connection is only created if it actually needed. This can be useful when combined with a framework plugin like L<CGI::Application::Plugin::Session>, which creates a CGI::Session object on demand as well.

C will override all the above arguments, if any present.

=item TableName

Name of the table session data will be stored in.

=back

=head1 LICENSING

For support and licensing information see L<CGI::Session|CGI::Session>

Package =

=head1 NAME

CGI::Session::Driver::db_file - CGI::Session driver for BerkeleyDB using DB_File

=head1 SYNOPSIS

$s = new CGI::Session("driver:db_file", $sid); $s = new CGI::Session("driver:db_file", $sid, {FileName=>'/tmp/cgisessions.db'});

=head1 DESCRIPTION

B stores session data in BerkelyDB file using L<DB_File|DB_File> - Perl module. All sessions will be stored in a single file, specified in I driver argument as in the above example. If I isn't given, defaults to F</tmp/cgisess.db>, or its equivalent on a non-UNIX system.

If the directory hierarchy leading to the file does not exist, will be created for you.

This module takes a B option which will be used if DB_File has to create the database file for you. By default the umask is 0660.

=head1 LICENSING

For support and licensing information see L<CGI::Session|CGI::Session>

Package =

extends CGI::Session::ErrorHandler

=head1 NAME

CGI::Session::Driver - CGI::Session driver specifications

=head1 WARNING

Version 4.0 of CGI::Session's driver specification is B backward compatible with previous specification. If you already have a driver developed to work with the previous version you're highly encouraged to upgrade your driver code to make it compatible with the current version. Fortunately, current driver specs are a lot easier to adapt to.

If you need any help converting your driver to meet current specs, send me an e-mail. For support information see L<CGI::Session|CGI::Session>

=head1 SYNOPSIS

require CGI::Session::Driver; @ISA = qw( CGI::Session::Driver );

=head1 DESCRIPTION

CGI::Session::Driver is a base class for all CGI::Session's native drivers. It also documents driver specifications for those willing to write drivers for different databases not currently supported by CGI::Session.

=head1 WHAT IS A DRIVER

Driver is a piece of code that helps CGI::Session library to talk to specific database engines, or storage mechanisms. To be more precise, driver is a F<.pm> file that inherits from CGI::Session::Driver and defines L<retrieve()|/"retrieve($self, $sid)">, L<store()|/"store($self, $sid, $datastr)"> and L<remove()|/"remove($self, $sid)"> methods.

=head2 BLUEPRINT

The best way of learning the specs is to look at a blueprint of a driver:

package CGI::Session::Driver::your_driver_name; use strict; use base qw( CGI::Session::Driver CGI::Session::ErrorHandler );

sub init { my ($self) = @_; # optional }

sub DESTROY { my ($self) = @_; # optional }

sub store { my ($self, $sid, $datastr) = @_; # Store $datastr, which is an already serialized string of data. }

sub retrieve { my ($self, $sid) = @_; # Return $datastr, which was previously stored using above store() method. # Return $datastr if $sid was found. Return 0 or "" if $sid doesn't exist }

sub remove { my ($self, $sid) = @_; # Remove storage associated with $sid. Return any true value indicating success, # or undef on failure. }

sub traverse { my ($self, $coderef) = @_; # execute $coderef for each session id passing session id as the first and the only # argument }

1;

All the attributes passed as the second argument to CGI::Session's new() or load() methods will automatically be made driver's object attributes. For example, if session object was initialized as following:

$s = CGI::Session->new("driver:your_driver_name", undef, {Directory=>'/tmp/sessions'});

You can access value of 'Directory' from within your driver like so:

sub store { my ($self, $sid, $datastr) = @_; my $dir = $self->{Directory}; # <-- in this example will be '/tmp/sessions' }

Optionally, you can define C<init()> method within your driver to do driver specific global initialization. C<init()> method will be invoked only once during the lifecycle of your driver, which is the same as the lifecycle of a session object.

For examples of C<init()> look into the source code of native CGI::Session drivers.

=head1 METHODS

This section lists and describes all driver methods. All the driver methods will receive driver object ($self) as the first argument. Methods that pertain to an individual session (such as C<retrieve()>, C<store()> and C<remove()>) will also receive session id ($sid) as the second argument.

Following list describes every driver method, including its argument list and what step of session's life they will be invoked. Understanding this may help driver authors.

=over 4

=item retrieve($self, $sid)

Called whenever a specific session is requested either via C<< CGI::Session->new() >> or C<< CGI::Session->load() >> syntax. Method should try to retrieve data associated with C< $sid > and return it. In case no data could be retrieved for C< $sid > 0 (zero) or "" should be returned. undef must be returned only to signal error. Error message should be set via set_error(), which can be inherited from L<CGI::Session::ErrorHandler|CGI::Session::ErrorHandler>.

Tip: set_error() always returns undef. Use it for your advantage.

=item store($self, $sid, $datastr)

Called whenever modified session data is to be stored back to disk. This happens whenever CGI::Session->flush() is called on modified session. Since CGI::Session->DESTROY() calls flush(), store() gets requested each time session object is to be terminated.

C< store() > is called both to store new sessions and to update already stored sessions. It's driver author's job to figure out which operation needs to be performed.

$datastr, which is passed as the third argument to represents B session data that needs to be saved.

store() can return any true value indicating success or undef on failure. Error message should be passed to set_error()

=item remove($self, $sid)

Called whenever session data is to be deleted, which is when CGI::Session->delete() is called. Should return any true value indicating success, undef on failure. Error message should be logged in set_error().

=item traverse($self, \&coderef)

Called only from within CGI::Session->find(). Job of traverse() is to call \&coderef for every single session stored in disk passing session's id as the first and only argument: C<< $coderef->( $sid ) >>

=item init($self)

Optional. Called whenever driver object is to be initialized, which happens only once during the lifecycle of CGI::Session object. Here you can do driver-wide initialization, such as to open connection to a database server.

=item DESTROY($self)

Optional. Perl automatically calls this method on objects just before they are to be terminated. This gives your driver chance to close any database connections or close any open file handles.

=back

=head2 NOTES

=over 4

=item *

All driver F<.pm> files must be lowercase!

=item *

DBI-related drivers are better off using L<CGI::Session::Driver::DBI|CGI::Session::Driver::DBI> as base, but don't have to.

=back

=head1 LICENSING

For support and licensing see L<CGI::Session|CGI::Session>.

Package =

=head1 NAME

CGI::Session::Driver::file - Default CGI::Session driver

=head1 SYNOPSIS

$s = new CGI::Session(); $s = new CGI::Session("driver:file", $sid); $s = new CGI::Session("driver:file", $sid, {Directory=>'/tmp'});

=head1 DESCRIPTION

When CGI::Session object is created without explicitly setting I, I will be assumed. I - driver will store session data in plain files, where each session will be stored in a separate file.

Naming conventions of session files are defined by C<$CGI::Session::Driver::file::FileName> global variable. Default value of this variable is I<cgisess_%s>, where %s will be replaced with respective session ID. Should you wish to set your own FileName template, do so before requesting for session object:

$CGI::Session::Driver::file::FileName = "%s.dat"; $s = new CGI::Session();

For backwards compatibility with 3.x, you can also use the variable name C<$CGI::Session::File::FileName>, which will override the one above.

=head2 DRIVER ARGUMENTS

If you wish to specify a session directory, use the B option, which denotes location of the directory where session ids are to be kept. If B is not set, defaults to whatever File::Spec->tmpdir() returns. So all the three lines in the SYNOPSIS section of this manual produce the same result on a UNIX machine.

If specified B does not exist, all necessary directory hierarchy will be created.

By default, sessions are created with a umask of 0660. If you wish to change the umask for a session, pass a B option with an octal representation of the umask you would like for said session.

=head1 NOTES

If your OS doesn't support flock, you should understand the risks of going without locking the session files. Since sessions tend to be used in environments where race conditions may occur due to concurrent access of files by different processes, locking tends to be seen as a good and very necessary thing. If you still want to use this driver but don't want flock, set C<$CGI::Session::Driver::file::NoFlock> to 1 or pass C<< NoFlock => 1 >> and this driver will operate without locks.

=head1 LICENSING

For support and licensing see L<CGI::Session|CGI::Session>

Package =

extends CGI::Session::Driver::DBI

=head1 NAME

CGI::Session::Driver::mysql - CGI::Session driver for MySQL database

=head1 SYNOPSIS

$s = new CGI::Session( "driver:mysql", $sid); $s = new CGI::Session( "driver:mysql", $sid, { DataSource => 'dbi:mysql:test', User => 'sherzodr', Password => 'hello' }); $s = new CGI::Session( "driver:mysql", $sid, { Handle => $dbh } );

=head1 DESCRIPTION

B stores session records in a MySQL table. For details see L<CGI::Session::Driver::DBI|CGI::Session::Driver::DBI>, its parent class.

It's especially important for the MySQL driver that the session ID column be defined as a primary key, or at least "unique", like this:

CREATE TABLE sessions ( id CHAR(32) NOT NULL PRIMARY KEY, a_session TEXT NOT NULL );

=head2 DRIVER ARGUMENTS

B driver supports all the arguments documented in L<CGI::Session::Driver::DBI|CGI::Session::Driver::DBI>. In addition, I argument can optionally leave leading "dbi:mysql:" string out:

$s = new CGI::Session( "driver:mysql", $sid, {DataSource=>'shopping_cart'}); # is the same as: $s = new CGI::Session( "driver:mysql", $sid, {DataSource=>'dbi:mysql:shopping_cart'});

=head2 BACKWARDS COMPATIBILITY

For backwards compatibility, you can also set the table like this before calling C<new()>. However, it is not recommended because it can cause conflicts in a persistent environment.

$CGI::Session::MySQL::TABLE_NAME = 'my_sessions';

=head1 LICENSING

For support and licensing see L<CGI::Session|CGI::Session>.

Package =

extends CGI::Session::Driver::DBI

=head1 NAME

CGI::Session::Driver::postgresql - PostgreSQL driver for CGI::Session

=head1 SYNOPSIS

use CGI::Session; $session = new CGI::Session("driver:PostgreSQL", undef, {Handle=>$dbh});

=head1 DESCRIPTION

CGI::Session::PostgreSQL is a L<CGI::Session|CGI::Session> driver to store session data in a PostgreSQL table.

=head1 STORAGE

Before you can use any DBI-based session drivers you need to make sure compatible database table is created for CGI::Session to work with. Following command will produce minimal requirements in most SQL databases:

CREATE TABLE sessions ( id CHAR(32) NOT NULL PRIMARY KEY, a_session BYTEA NOT NULL );

and within your code use:

use CGI::Session; $session = new CGI::Session("driver:PostgreSQL", undef, {Handle=>$dbh, ColumnType=>"binary"});

Please note the I argument. PostgreSQL's text type has problems when trying to hold a null character. (Known as C<"\0"> in Perl, not to be confused with SQL I). If you know there is no chance of ever having a null character in the serialized data, you can leave off the I attribute. Using a I column type and C<< ColumnType => 'binary' >> is recommended when using L<Storable|CGI::Session::Serialize::storable> as the serializer or if there's any possibility that a null value will appear in any of the serialized data.

For more details see L<CGI::Session::Driver::DBI|CGI::Session::Driver::DBI>, parent class.

Also see L, which exercises different method for dealing with binary data.

=head1 COPYRIGHT

Copyright (C) 2002 Cosimo Streppone. All rights reserved. This library is free software and can be modified and distributed under the same terms as Perl itself.

=head1 AUTHORS

Cosimo Streppone <cosimo@cpan.org>, heavily based on the CGI::Session::MySQL driver by Sherzod Ruzmetov, original author of CGI::Session.

Matt LeBlanc contributed significant updates for the 4.0 release.

=head1 LICENSING

For additional support and licensing see L<CGI::Session|CGI::Session>

Package =

=head1 NAME

CGI::Session::Driver::sqlite - CGI::Session driver for SQLite

=head1 SYNOPSIS

$s = new CGI::Session("driver:sqlite", $sid, {DataSource=>'/my/folder/sessions.sqlt'}); $s = new CGI::Session("driver:sqlite", $sid, {Handle=>$dbh});

=head1 DESCRIPTION

B driver stores session data in SQLite files using L<DBD::SQLite|DBD::SQLite> DBI driver. More details see L<CGI::Session::Driver::DBI|CGI::Session::Driver::DBI>, its parent class.

=head1 DRIVER ARGUMENTS

Supported driver arguments are I and I. B only one of these arguments can be set while creating session object.

I should be in the form of C<dbi:SQLite:dbname=/path/to/db.sqlt>. If C<dbi:SQLite:> is missing it will be prepended for you. If I is present it should be database handle (C<$dbh>) returned by L<DBI::connect()|DBI/connect()>.

As of version 1.7 of this driver, the third argument is B optional. Using a default database in the temporary directory is a security risk since anyone on the machine can create and/or read your session data. If you understand these risks and still want the old behavior, you can set the C option to I<'/tmp/sessions.sqlt'>.

=head1 BUGS AND LIMITATIONS

None known.

=head1 LICENSING

For support and licensing see L<CGI::Session|CGI::Session>

Package =

=head1 NAME

CGI::Session::ErrorHandler - error handling routines for CGI::Session

=head1 SYNOPSIS

require CGI::Session::ErrorHandler @ISA = qw( CGI::Session::ErrorHandler );

sub some_method { my $self = shift; unless ( $some_condition ) { return $self->set_error("some_method(): \$some_condition isn't met"); } }

=head1 DESCRIPTION

CGI::Session::ErrorHandler provides set_error() and errstr() methods for setting and accessing error messages from within CGI::Session's components. This method should be used by driver developers for providing CGI::Session-standard error handling routines for their code

=head2 METHODS

=over 4

=item set_error($message)

Implicitly defines $pkg_name::errstr and sets its value to $message. Return value is B undef.

Package =

extends CGI::Session::ErrorHandler

=head1 NAME

CGI::Session::ID::incr - CGI::Session ID driver

=head1 SYNOPSIS

use CGI::Session; $session = new CGI::Session("id:Incr", undef, { Directory => '/tmp', IDFile => '/tmp/cgisession.id', IDInit => 1000, IDIncr => 2 });

=head1 DESCRIPTION

CGI::Session::ID::incr is to generate auto incrementing Session IDs. Compare it with L<CGI::Session::ID::md5|CGI::Session::ID::md5>, where session ids are truly random 32 character long strings. CGI::Session::ID::incr expects the following arguments passed to CGI::Session->new() as the third argument.

=over 4

=item IDFile

Location where auto incremented IDs are stored. This attribute is required.

=item IDInit

Initial value of the ID if it's the first ID to be generated. For example, if you want the ID numbers to start with 1000 as opposed to 0, that's where you should set your value. Default is C<0>.

=item IDIncr

How many digits each number should increment by. For example, if you want the first generated id to start with 1000, and each subsequent id to increment by 10, set I to 10 and I to 1000. Default is C<1>.

=back

=head1 LICENSING

For support and licensing information see L<CGI::Session|CGI::Session>

Package =

extends CGI::Session::ErrorHandler

=head1 NAME

CGI::Session::ID::md5 - default CGI::Session ID generator

=head1 SYNOPSIS

use CGI::Session; $s = new CGI::Session("id:md5", undef);

=head1 DESCRIPTION

CGI::Session::ID::MD5 is to generate MD5 encoded hexadecimal random ids. The library does not require any arguments.

=head1 LICENSING

For support and licensing see L<CGI::Session|CGI::Session>

Package =

=head1 NAME

CGI::Session::Serialize::default - Default CGI::Session serializer

=head1 DESCRIPTION

This library is used by CGI::Session driver to serialize session data before storing it in disk.

All the methods are called as class methods.

=head1 METHODS

=over 4

=item freeze($class, \%hash)

Receives two arguments. First is the class name, the second is the data to be serialized. Should return serialized string on success, undef on failure. Error message should be set using C<set_error()|CGI::Session::ErrorHandler/"set_error()">

=item thaw($class, $string)

Received two arguments. First is the class name, second is the I data string. Should return thawed data structure on success, undef on failure. Error message should be set using C<set_error()|CGI::Session::ErrorHandler/"set_error()">

=back

=head1 LICENSING

For support and licensing see L<CGI::Session|CGI::Session>

Package =

=head1 NAME

CGI::Session::Serialize::freezethaw - serializer for CGI::Session

=head1 DESCRIPTION

This library can be used by CGI::Session to serialize session data. Uses L<FreezeThaw|FreezeThaw>.

=head1 METHODS

=over 4

=item freeze($class, \%hash)

Receives two arguments. First is the class name, the second is the data to be serialized. Should return serialized string on success, undef on failure. Error message should be set using C<set_error()|CGI::Session::ErrorHandler/"set_error()">

=item thaw($class, $string)

Received two arguments. First is the class name, second is the I data string. Should return thawed data structure on success, undef on failure. Error message should be set using C<set_error()|CGI::Session::ErrorHandler/"set_error()">

=back

=head1 LICENSING

For support and licensing see L<CGI::Session|CGI::Session>

Package =

=head1 NAME

CGI::Session::Serialize::json - serializer for CGI::Session

=head1 DESCRIPTION

This library can be used by CGI::Session to serialize session data. Requires L<JSON::Syck|JSON::Syck>. JSON is a type of L<YAML|CGI::Session::Serialize::yaml>, with one extension: serialized JSON strings are actually valid JavaScript code that a browser can execute. Any langauge that has a YAML parser (Perl, PHP, Python, Ruby, C, etc) can also read data that has been serialized with JSON.

=head1 METHODS

=over 4

=item freeze($class, \%hash)

Receives two arguments. First is the class name, the second is the data to be serialized. Should return serialized string on success, undef on failure. Error message should be set using C<set_error()|CGI::Session::ErrorHandler/"set_error()">

=item thaw($class, $string)

Received two arguments. First is the class name, second is the I data string. Should return thawed data structure on success, undef on failure. Error message should be set using C<set_error()|CGI::Session::ErrorHandler/"set_error()">

=back

=head1 SEE ALSO

L<CGI::Session>, L<JSON::Syck>.

Package =

=head1 NAME

CGI::Session::Serialize::storable - Serializer for CGI::Session

=head1 DESCRIPTION

This library can be used by CGI::Session to serialize session data. Uses L<Storable|Storable>.

=head1 METHODS

=over 4

=item freeze($class, \%hash)

Receives two arguments. First is the class name, the second is the data to be serialized. Should return serialized string on success, undef on failure. Error message should be set using C<set_error()|CGI::Session::ErrorHandler/"set_error()">

Package =

=head1 NAME

CGI::Session::Serialize::yaml - serializer for CGI::Session

=head1 DESCRIPTION

This library can be used by CGI::Session to serialize session data. It uses L<YAML|YAML>, or the faster C implementation, L<YAML::Syck|YAML::Syck> if it is available. YAML serializers exist not just for Perl but also other dynamic languages, such as PHP, Python, and Ruby, so storing session data in this format makes it easy to share session data across different languages.

YAML is made to be friendly for humans to parse as well as other computer languages. It creates a format that is easier to read than the default serializer.

=head1 METHODS

=over 4

=item freeze($class, \%hash)

Receives two arguments. First is the class name, the second is the data to be serialized. Should return serialized string on success, undef on failure. Error message should be set using C<set_error()|CGI::Session::ErrorHandler/"set_error()">

=item thaw($class, $string)

Received two arguments. First is the class name, second is the I data string. Should return thawed data structure on success, undef on failure. Error message should be set using C<set_error()|CGI::Session::ErrorHandler/"set_error()">

=back

=head1 SEE ALSO

L<CGI::Session>, L, L<YAML::Syck>.

Package =

=head1 NAME

CGI::Session::Tutorial - Extended CGI::Session manual

=head1 STATE MAINTENANCE OVERVIEW

Since HTTP is a stateless protocol, each subsequent click to a web site is treated as new request by the Web server. The server does not relate a visit with a previous one, thus all the state information from the previous requests are lost. This makes creating such applications as shopping carts, web sites requiring users to authenticate, impossible. So people had to do something about this despair situation HTTP was putting us in.

For our rescue come such technologies as I and Is that help us save the users' session for a certain period. Since I and Is alone cannot take us too far (B), several other libraries have been developed to extend their capabilities and promise a more reliable solution. L<CGI::Session|CGI::Session> is one of them.

Before we discuss this library, let's look at some alternative solutions.

=head2 COOKIE

Cookie is a piece of text-information that a web server is entitled to place in the user's hard disk, assuming a user agent (such as Internet Explorer, Mozilla, etc) is compatible with the specification. After the cookie is placed, user agents are required to send these cookies back to the server as part of the HTTP request. This way the server application ( CGI, for example ) will have a way of relating previous requests by the same user agent, thus overcoming statelessness of HTTP.

Although I seem to be promising solution for the statelessness of HTTP, they do carry certain limitations, such as limited number of cookies per domain and per user agent and limited size on each cookie. User Agents are required to store at least 300 cookies at a time, 20 cookies per domain and allow 4096 bytes of storage for each cookie. They also rise several Privacy and Security concerns, the lists of which can be found on the sections B<6-"Privacy"> and B<7-"Security Considerations"> of B.

=head2 QUERY STRING

Query string is a string appended to URL following a question mark (?) such as:

http://my.dot.com/login.cgi?user=sherzodr;password=top-secret

As you probably guessed, it can also help you pass state information from a click to another, but how secure is it do you think, considering these URLs tend to get cached by most of the user agents and also logged in the servers access log, to which everyone can have access.

=head2 HIDDEN FIELDS

Hidden field is another alternative to using query strings and they come in two flavors: hidden fields used in POST methods and the ones in GET. The ones used in GET methods will turn into a true query strings once submitted, so all the disadvantages of QUERY_STRINGs apply. Although POST requests do not have limitations of its sister-GET, the pages that hold them get cached by Web browser, and are available within the source code of the page (obviously). They also become unwieldily to manage when one has oodles of state information to keep track of ( for instance, a shopping cart or an advanced search engine).

Query strings and hidden fields are also lost easily by closing the browser, or by clicking the browser's "Back" button.

=head2 SERVER SIDE SESSION MANAGEMENT

This technique is built upon the aforementioned technologies plus a server-side storage device, which saves the state data on the server side. Each session has a unique id associated with the data in the server. This id is also associated with the user agent either in the form of a I, a I, hidden field or any combination of the above. This is necessary to make the connection with the client and his data.

Advantages:

=over 4

=item *

We no longer need to depend on User Agent constraints in cookie size.

=item *

Sensitive data no longer need to be traveling across the network at each request (which is the case with query strings, cookies and hidden fields). The only thing that travels is the unique id generated for the session (B<5767393932698093d0b75ef614376314>, for instance), which should make no sense to third parties.

=item *

User will not have sensitive data stored in his/her computer in unsecured file (which is a cookie file).

=item *

It's possible to handle very big and even complex data structures transparently (which I do not handle).

=back

That's what CGI::Session is all about - implementing server side session management. Now is a good time to get feet wet.

=head1 PROGRAMMING STYLE

Server side session management system might be seeming awfully convoluted if you have never dealt with it. Fortunately, with L<CGI::Session|CGI::Session> all the complexity is handled by the library transparently. This section of the manual can be treated as an introductory tutorial to both logic behind session management, and to CGI::Session programming style.

All applications making use of server side session management rely on the following pattern of operation regardless of the way the system is implemented:

=over 4

=item 1

Check if the user has session cookie dropped in his computer from previous request

=item 2

If the cookie does not exist, create a new session identifier, and drop it as cookie to the user's computer.

=item 3

If session cookie exists, read the session ID from the cookie and load any previously saved session data from the server side storage. If session had any expiration date set it's useful to re-drop the same cookie to the user's computer so its expiration time will be reset to be relative to user's last activity time.

=item 4

Store any necessary data in the session that you want to make available for the next HTTP request.

=back

CGI::Session will handle all of the above steps. All you have to do is to choose what to store in the session.

=head2 GETTING STARTED

To make L<CGI::Session|CGI::Session>'s functionality available in your program do either of the following somewhere on top of your program file:

use CGI::Session; # or require CGI::Session;

Whenever you're ready to create a new session in your application, do the following:

$session = new CGI::Session() or die CGI::Session->errstr;

Above line will first try to re-initialize an existing session by consulting cookies and necessary QUERY_STRING parameters. If it fails will create a brand new session with a unique ID, which is normally called I, I for short, and can be accessed through L<id()|CGI::Session/id()> - object method.

We didn't check for any session cookies above, did we? No, we didn't, but CGI::Session did. It looked for a cookie called C, and if it found it tried to load existing session from server side storage (B in our case). If cookie didn't exist it looked for a QUERY_STRING parameter called C. If all the attempts to recover session ID failed, it created a new session.

NOTE: For the above syntax to work as intended your application needs to have write access to your computer's I folder, which is usually F in UNIX. If it doesn't, or if you wish to store this application's session files in a different place, you may pass the third argument like so:

$session = new CGI::Session(undef, undef, {Directory=>'../tmp/sessions'});

Now it will store all the newly created sessions in (and will attempt to initialize requested sessions from) that folder. Don't worry if the directory hierarchy you want to use doesn't already exist. It will be created for you. For details on how session data are stored refer to L<CGI::Session::Driver::file|CGI::Session::Driver::file>, which is the default driver used in our above example.

There is one small, but very important thing your application needs to perform after creating CGI::Session object as above. It needs to drop Session ID as an I into the user's computer. CGI::Session will use this cookie to identify the user at his/her next request and will be able to load his/her previously stored session data.

To make sure CGI::Session will be able to read your cookie at next request you need to consult its C<name()> method for cookie's suggested name:

$cookie = $query->cookie( -name => $session->name, -value => $session->id ); print $query->header( -cookie=>$cookie );

C<name()> returns C by default. If you prefer a different cookie name, you can change it as easily too, but you have to do it before CGI::Session object is created:

CGI::Session->name("SID"); $session = new CGI::Session();

Baking the cookie wasn't too difficult, was it? But there is an even easier way to send a cookie using CGI::Session:

print $session->header();

The above will create the cookie using L<CGI::Cookie|CGI::Cookie> and will return proper http headers using L<CGI.pm|CGI>'s L<CGI|CGI/header()> method. Any arguments to L<CGI::Session|CGI::Session/header()> will be passed to L<CGI::header()|CGI/header()>.

Of course, this method of initialization will only work if client is accepting cookies. If not you would have to pass session ID in each URL of your application as QUERY_STRING. For CGI::Session to detect it the name of the parameter should be the same as returned by L<name()|CGI::Session/name()>:

printf ("click me", $session->name, $session->id);

If you already have session id to be initialized you may pass it as the only argument, or the second argument of multi-argument syntax:

$session = new CGI::Session( $sid ); $session = new CGI::Session( "serializer:freezethaw", $sid ); $session = new CGI::Session( "driver:mysql", $sid, {Handle=>$dbh} );

By default CGI::Session uses standard L<CGI|CGI> to parse queries and cookies. If you prefer to use a different, but compatible object you can pass that object in place of $sid:

$cgi = new CGI::Simple(); $session = new CGI::Session ( $cgi ); $session = new CGI::Session( "driver:db_file;serializer:storable", $cgi); # etc

See L<CGI::Simple|CGI::Simple>

=head2 STORING DATA

L<CGI::Session|CGI::Session> offers L<param() method|CGI::Session/param()>, which behaves exactly as L<CGI.pm's param()|CGI/param()> with identical syntax. L<param()|CGI::Session/param()> is used for storing data in session as well as for accessing already stored data.

Imagine your customer submitted a login form on your Web site. You, as a good host, wanted to remember the guest's name, so you can a) greet him accordingly when he visits your site again, or b) to be helpful by filling out I part of his login form, so the customer can jump right to the I field without having to type his username again.

my $name = $cgi->param('username'); $session->param('username', $name);

Notice, we're grabbing I value of the field using CGI.pm's (or another compatible library's) C<param()> method, and storing it in session using L<CGI::Session|CGI::Session>'s L<param()|CGI::Session/param()> method.

If you have too many stuff to transfer into session, you may find yourself typing the above code over and over again. I've done it, and believe me, it gets very boring too soon, and is also error-prone. So we introduced the following handy method:

$session->save_param(['name']);

If you wanted to store multiple form fields just include them all in the second list:

$session->save_param(['name', 'email']);

If you want to store all the available I parameters you can omit the arguments:

$session->save_param();

See L<save_param()|CGI::Session/save_param> for more details.

When storing data in the session you're not limited to strings. You can store arrays, hashes and even most objects. You will need to pass them as references (except objects).

For example, to get all the selected values of a scrolling list and store it in the session:

my @fruits = $cgi->param('fruits'); $session->param('fruits', \@fruits);

For parameters with multiple values save_param() will do the right thing too. So the above is the same as:

$session->save_param($cgi, ['fruits']);

All the updates to the session data using above methods will not reflect in the data store until your application exits, or C<$session> goes out of scope. If, for some reason, you need to commit the changes to the data store before your application exits you need to call L<flush()|CGI::Session/flush()> method:

$session->flush();

I've written a lot of code, and never felt need for using C<flush()> method, since CGI::Session calls this method at the end of each request. There are, however, occasions I can think of one may need to call L<flush()|CGI::Session/flush()>.

=head2 ACCESSING STORED DATA

There's no point of storing data if you cannot access it. You can access stored session data by using the same L<param() method|CGI::Session/param()> you once used to store them. Remember the Username field from the previous section that we stored in the session? Let's read it back so we can partially fill the Login form for the user:

$name = $session->param("name"); printf "", $name;

To retrieve previously stored @fruits do not forget to de reference it:

@fruits = @{ $session->param('fruits') };

Very frequently, you may find yourself having to create pre-filled and pre-selected forms, like radio buttons, checkboxes and drop down menus according to the user's preferences or previous action. With text and textareas it's not a big deal - you can simply retrieve a single parameter from the session and hard code the value into the text field. But how would you do it when you have a group of radio buttons, checkboxes and scrolling lists? For this purpose, CGI::Session provides L<load_param()|CGI::Session/load_param()> method, which loads given session parameters to a CGI object (assuming they have been previously saved with L<save_param()|CGI::Session/save_param()> or alternative):

$session->load_param($cgi, ["fruits"]);

Now when you say:

print $cgi->checkbox_group(fruits=>['apple', 'banana', 'apricot']);

See L<load_param()|CGI::Session/load_param()> for details.

Generated checkboxes will be pre-filled using previously saved information. To see example of a real session-powered application consider http://handalak.com/cgi-bin/subscriptions.cgi

If you're making use of L<HTML::Template|HTML::Template> to separate the code from the skin, you can as well associate L<CGI::Session|CGI::Session> object with HTML::Template and access all the parameters from within HTML files. We love this trick!

$template = new HTML::Template(filename=>"some.tmpl", associate=>$session); print $template->output();

Assuming the session object stored "first_name" and "email" parameters while being associated with HTML::Template, you can access those values from within your "some.tmpl" file now:

Hello !

See L<HTML::Template's online manual|HTML::Template> for details.

=head2 CLEARING SESSION DATA

You store session data, you access session data and at some point you will want to clear certain session data, if not all. For this purpose L<CGI::Session|CGI::Session> provides L<clear()|CGI::Session/clear()> method which optionally takes one argument as an arrayref indicating which session parameters should be deleted from the session object:

$session->clear(["~logged-in", "email"]);

Above line deletes "~logged-in" and "email" session parameters from the session. And next time you say:

$email = $session->param("email");

it returns undef. If you omit the argument to L<clear()|CGI::Session/clear()>, be warned that all the session parameters you ever stored in the session object will get deleted. Note that it does not delete the session itself. Session stays open and accessible. It's just the parameters you stored in it gets deleted

See L<clear()|CGI::Session/clear()> for details.

=head2 DELETING A SESSION

If there's a start there's an end. If session could be created, it should be possible to delete it from the disk for good:

$session->delete();

The above call to L<delete()|CGI::Session/delete()> deletes the session from the disk for good. Do not confuse it with L<clear()|CGI::Session/clear()>, which only clears certain session parameters but keeps the session open.

See L<delete()|CGI::Session/delete()> for details.

=head2 EXPIRATION

L<CGI::Session|CGI::Session> provides limited means to expire sessions. Expiring a session is the same as deleting it via delete(), but deletion takes place automatically. To expire a session, you need to tell the library how long the session would be valid after the last access time. When that time is met, CGI::Session refuses to retrieve the session. It deletes the session and returns a brand new one. To assign expiration ticker for a session, use L<expire()|CGI::Session/expire()>:

$session->expire(3600); # expire after 3600 seconds $session->expire('+1h'); # expire after 1 hour $session->expire('+15m'); # expire after 15 minutes $session->expire('+1M'); # expire after a month and so on.

When session is set to expire at some time in the future, but session was not requested at or after that time has passed it will remain in the disk. When expired session is requested CGI::Session will remove the data from disk, and will initialize a brand new session.

See L<expire()|CGI::Session/expire()> for details.

Before CGI::Session 4.x there was no way of intercepting requests to expired sessions. CGI::Session 4.x introduced new kind of constructor, L<load()|CGI::Session/load()>, which is identical in use to L<new()|CGI::Session/new()>, but is not allowed to create sessions. It can only load them. If session is found to be expired, or session does not exist it will return an empty CGI::Session object. And if session is expired, in addition to being empty, its status will also be set to expired. You can check against these conditions using L<empty()|CGI::Session/empty()> and L<is_expired()|CGI::Session/is_expired()> methods. If session was loaded successfully object returned by C<load()> is as good a session as the one returned by C<new()>:

$session = CGI::Session->load() or die CGI::Session->errstr; if ( $session->is_expired ) { die "Your session expired. Please refresh your browser to re-start your session"; } if ( $session->is_empty ) { $session = $session->new(); }

Above example is worth an attention. Remember, all expired sessions are empty sessions, but not all empty sessions are expired sessions. Following this rule we have to check with C<is_expired()> before checking with C<is_empty()>. There is another thing about the above example. Notice how its creating new session when un existing session was requested? By calling C<new()> as an object method! Handy thing about that is, when you call C<new()> on a session object new object will be created using the same configuration as the previous object.

For example:

$session = CGI::Session->load("driver:mysql;serializer:storable", undef, {Handle=>$dbh}); if ( $session->is_expired ) { die "Your session is expired. Please refresh your browser to re-start your session"; } if ( $session->is_empty ) { $session = $session->new(); }

Initial C<$session> object was configured with B as the driver, B as the serializer and B<$dbh> as the database handle. Calling C< new() > on this object will return an object of the same configuration. So C< $session > object returned from C< new() > in the above example will use B as the driver, B as the serializer and B<$dbh> as the database handle.

See L<is_expired()|CGI::Session/is_expired()>, L<is_empty()|CGI::Session/is_empty()>, L<load()|CGI::Session/load()> for details.

Sometimes it makes perfect sense to expire a certain session parameter, instead of the whole session. I usually do this in my login enabled sites, where after the user logs in successfully, I set his/her "_logged_in" session parameter to true, and assign an expiration ticker on that flag to something like 30 minutes. It means, after 30 idle minutes CGI::Session will L<clear|CGI::Session/clear()> "_logged_in" flag, indicating the user should log in over again. I agree, the same effect can be achieved by simply expiring() the session itself, but by doing this we would loose other session parameters, such as user's shopping cart, session-preferences and the like.

This feature can also be used to simulate layered authentication, such as, you can keep the user's access to his/her personal profile information for as long as 60 minutes after a successful login, but expire his/her access to his credit card information after 5 idle minutes. To achieve this effect, we will use L<expire()|CGI::Session/expire()> method again:

$session->expire(_profile_access, '1h'); $session->expire(_cc_access, '5m');

With the above syntax, the person will still have access to his personal information even after 5 idle hours. But when he tries to access or update his/her credit card information, he may be displayed a "login again, please" screen.

See L<expire()|CGI::Session/expire()> for details.

This concludes our discussion of CGI::Session programming style. The rest of the manual covers some L<"SECURITY"> issues. Driver specs from the previous manual were moved to L<CGI::Session::Driver|CGI::Session::Driver>.

=head1 SECURITY

"How secure is using CGI::Session?", "Can others hack down people's sessions using another browser if they can get the session id of the user?", "Are the session ids easy to guess?" are the questions I find myself answering over and over again.

=head2 STORAGE

Security of the library does in many aspects depend on the implementation. After making use of this library, you no longer have to send all the information to the user's cookie except for the session id. But, you still have to store the data in the server side. So another set of questions arise, can an evil person get access to session data in your server, even if he does, can he make sense out of the data in the session file, and even if he can, can he reuse the information against a person who created that session. As you see, the answer depends on yourself who is implementing it.

=over 4

=item *

First rule of thumb, do not store users' passwords or other sensitive data in the session, please. If you have to, use one-way encryption, such as md5, or SHA-1-1. For my own experience I can assure you that in properly implemented session-powered Web applications there is never a need for it.

=item *

Default configuration of the driver makes use of L<Data::Dumper|Data::Dumper> class to serialize data to make it possible to save it in the disk. Data::Dumper's result is a human readable data structure, which, if opened, can be interpreted easily. If you configure your session object to use either L<Storable|CGI::Session::Serialize::storable> or L<FreezeThaw|CGI::Session::Serialize::freezethaw> as a serializer, this would make it more difficult for bad guys to make sense out of session data. But don't use this as the only precaution. Since evil fingers can type a quick program using L<Storable|Storable> or L<FreezeThaw|FreezeThaw> to decipher session files very easily.

=item *

Do not allow anyone to update contents of session files. If you're using L serialized data string needs to be eval()ed to bring the original data structure back to life. Of course, we use L<Safe|Safe> to do it safely, but your cautiousness does no harm either.

=item *

Do not keep sessions open for very long. This will increase the possibility that some bad guy may have someone's valid session id at a given time (acquired somehow). To do this use L<expire()|CGI::Session/expire()> method to set expiration ticker. The more sensitive the information on your Web site is, the sooner the session should be set to expire.

=back

=head2 SESSION IDs

Session ids are not easily guessed (unless you're using L)! Default configuration of CGI::Session uses L<Digest::MD5|CGI::Session::ID::md5> to generate random, 32 character long identifier. Although this string cannot be guessed as easily by others, if they find it out somehow, can they use this identifier against the other person?

Consider the scenario, where you just give someone either via email or an instant messaging a link to a Web site where you're currently logged in. The URL you give to that person contains a session id as part of a query string. If the site was initializing the session solely using query string parameter, after clicking on that link that person now appears to that site as you, and might have access to all of your private data instantly.

Even if you're solely using cookies as the session id transporters, it's not that difficult to plant a cookie in the cookie file with the same id and trick the web browser to send that particular session id to the server. So key for security is to check if the person who's asking us to retrieve a session data is indeed the person who initially created the session data.

One way to help with this is by also checking that the IP address that the session is being used from is always same. However, this turns out not to be practical in common cases because some large ISPs (such as AOL) use proxies which cause each and every request from the same user to come from different IP address.

If you have an application where you are sure your users' IPs are constant during a session, you can consider enabling an option to make this check:

use CGI::Session ( '-ip_match' );

For backwards compatibility, you can also achieve this by setting $CGI::Session::IP_MATCH to a true value. This makes sure that before initializing a previously stored session, it checks if the ip address stored in the session matches the ip address of the user asking for that session. In which case the library returns the session, otherwise it dies with a proper error message.

=head1 LICENSING

For support and licensing see L<CGI::Session|CGI::Session>

Change E-mail Address

This form is used to change your registered e-mail addresses. Your registered e-mails are used by TWiki for sending you e-mails, including notifications of password changes. The addresses you register via this form are kept secret and will not be published anywhere on this site.

ALERT! Security Note: You really ought to register a valid e-mail address. If TWiki can't find a registered e-mail for you in the secret database, it will look in your user topic for a line like this:

   * Set Email = user@example.com
If your user topic is not protected from changes by other people, and you don't register an e-mail address using this form, then your user account could be hijacked by someone else.

If your old e-mail addresses are all invalid (you can't receive mail there any more) and you have forgotten your password, please contact ivoadoc@ivoa.net for help.

After submitting this form your e-mail will be changed, and you will be returned to this form.
Registered e-mail addresses for currently logged in user (TWikiGuest):
  Fields marked ** are required
Your LoginName: **
Password: **
New e-mails (space-separated list): **
 

Related topics: ChangePassword, ResetPassword, UserToolsCategory, AdminToolsCategory

Class Method

A ClassMethod is a method that must be called relative to the containing class object. This normally only applies to the new method used to create new object instances. For example,

package Telecoms

ClassMethod new()

my $mobile = new Telecoms();
or
my $mobile = Telecoms->new();

Related Topics: StaticMethod, ObjectMethod, DeveloperDocumentationCategory

Classic Skin

The classic TWiki skin is a bare bone and functional skin, supporting any browser, and has a minimum of graphics

This is not really a skin. It is the set of default templates, shown if no skin is activated. The default templates are part of every TWiki distribution.

Skin Info

Description: The classic TWiki skin, bare bone and functional, for any browser, with a minimum of graphics
Screenshot: Click for full screen image
Base Name: classic
Skin Author: TWiki:Main/PeterThoeny
Skin Version: 03 Aug 2008
Change History:  
03 May 2008 TWiki 4.2.1 release version
21 May 2007 Bugs:Item3969 - 8bit email fix (TWiki:Main.WillNorris)
25 Jul 2004: Initial version (v1.000)
Dependencies:  
Skin Home: http://TWiki.org/cgi-bin/view/Plugins/ClassicSkin
Feedback: http://TWiki.org/cgi-bin/view/Plugins/ClassicSkinDev

Note: The Description, Screenshot and Base Name rows are needed by the TWikiSkinBrowser

Related topic: TWikiSkins, TWikiSkinBrowser

-- TWiki:Main/PeterThoeny - 25 Jul 2004

Color Picker Plugin

screenshot-edit.png %SHORTDESCRIPTION%

Introduction

This TWiki plugin packages the Farbtastic color picker, which is a jQuery plugin developed by Steven Wittens of Acko.net. The package adds a color picker to TWiki forms and TWiki applications.

Using the color picker in TWikiForms

This package adds a color type to TWikiForms:

Type Description Size Value
color Single-line text box and a color picker to pick a color. The color can also be typed into the text box, such as #123456. Text box width in number of characters Initial (default) color

Example form definition:

Name: Type: Size Values: Tooltip message:
Background color color 12   Select color

Using the color picker in an HTML form

You can also use the color picker directly in your HTML forms, without having to write any code. Just include this in the topic text:

<form action="...">
%COLORPICKER{ name="text_color" size="12" value="#123456" class="twikiInputField" }%
<form>
This will show an HTML input field named "text_color" and a color picker tied to it. The size, value and class parameters are optional. Additional parameters can be supplied; they will be added to the HTML input field.

Test: (this only works if the ColorPickerPlugin is installed and enabled)

Using the color picker with disabled plugin

It is also possible to use the color picker in HTML forms with disabled ColorPickerPlugin:

%INCLUDE{ "%SYSTEMWEB%.ColorPickerPlugin" section="code" }%
<form action="...">
%INCLUDE{ "%SYSTEMWEB%.ColorPickerPlugin" section="picker" NAME="demo_color" SIZE="12" VALUE="#123456" EXTRA="class=\"twikiInputField\"" }%
</form>
This will show an HTML input field named "demo_color" and a color picker tied to it. The "code" section should be included once per topic, the "picker" section can be included as many times as needed. The NAME parameter is required; SIZE, VALUE and EXTRA parameters are optional. Use the EXTRA parameter to add additional parameters to the HTML input field.

Test: (this works only if the ColorPickerPlugin is installed and disabled)

Detailed Documentation

This package includes a small Perl module to make it easier to use the color picker from other TWiki plugins. This module includes the functions:

addHEAD

TWiki::Plugins::ColorPickerPlugin::addHEAD( )

addHEAD needs to be called before TWiki::Plugins::ColorPickerPlugin::renderForEdit is called.

renderForEdit

TWiki::Plugins::ColorPickerPlugin::renderForEdit($name, $value, [, \%options]) -> $html

Installation Instructions

You do not need to install anything in the browser to use this extension. The following instructions are for the administrator who installs the extension on the server where TWiki is running.

Like many other TWiki extensions, this module is shipped with a fully automatic installer script written using the BuildContrib.

  • If you have TWiki 4.2 or later, you can install from the configure interface (Go to Plugins->Find More Extensions)
  • If you have any problems, then you can still install manually from the command-line:
    1. Download one of the .zip or .tgz archives
    2. Unpack the archive in the root directory of your TWiki installation.
    3. Run the installer script ( perl <module>_installer )
    4. Run configure and enable the module, if it is a plugin.
    5. Repeat for any missing dependencies.
  • If you are still having problems, then instead of running the installer script:
    1. Make sure that the file permissions allow the webserver user to access all files.
    2. Check in any installed files that have existing ,v files in your existing install (take care not to lock the files when you check in)
    3. Manually edit LocalSite.cfg to set any configuration variables.

Plugin Info

  • Set SHORTDESCRIPTION = Color picker for use in TWiki forms and TWiki applications

Author: TWiki:Main.PeterThoeny, Twiki Inc
Copyright: © 2007 Steven Wittens, Acko.net for Farbtastic jQuery plugin
© 2010-2011 TWiki:Main.PeterThoeny and TWiki:TWiki.TWikiContributor for TWiki ColorPickerPlugin
License: GPL (GNU General Public License)
Dependencies:
NameVersionDescription
TWiki::Plugins::JQueryPlugin>=1.0Required; download from TWiki:Plugins/JQueryPlugin
Version: 21489 (2011-08-20)
Change History:  
2011-06-11: TWikibug:Item6725: Change global package variables from "use vars" to "our"
2010-11-30: TWikibug:Item6610: Rewrite ColorPickerContrib into ColorPickerPlugin
2010-11-27: TWikibug:Item6609: In TWikiForms type table, automatically list the color form field type defined in this contrib -- TWiki:Main.PeterThoeny
2010-11-26: TWikibug:Item6606: Complete rewrite of contrib using Farbtastic color picker -- TWiki:Main.PeterThoeny
2006-10-27: Initial version of ColorPickerContrib by TWiki:Main.FlavioCurti using Colorpicker by Norman Timmler (inlet media e.K., Hamburg, Germany)
Home: http://TWiki.org/cgi-bin/view/Plugins/ColorPickerPlugin
Feedback: http://TWiki.org/cgi-bin/view/Plugins/ColorPickerPluginDev
Appraisal: http://TWiki.org/cgi-bin/view/Plugins/ColorPickerPluginAppraisal

Related Topics: TWikiPreferences, TWikiForms, TWikiPlugins

Comment Plugin

The Comment Plugin lets users quickly post comments to a page without an edit/preview/save cycle.

Related topics: CommentPluginTemplates, CommentPluginExamples

Features

Inserts an edit box into the page that allows users to type in and save comments. Comments can be made

  • in different formats (as defined by a template),
  • in both forward and reverse chronological order,
  • signed or unsigned, dated or undated (as defined by a template),
  • in other topics, or other positions within the current topic.

Syntax

Write %COMMENT{attributes}% anywhere in a TWiki topic.

  • A %COMMENT% without parameters shows a simple text box.
  • A %COMMENT{}% can handle the following parameters:
    Parameter Description Default
    type This is the name of the template to use for this comment. Comment templates are defined in a TWiki template - see customization. If this attribute is not defined, the type is whatever is defined by COMMENTPLUGIN_DEFAULT_TYPE, either in this topic or in your WebPreferences. "below"
    default Default text to put into the textarea of the prompt.  
    target Name of the topic to add the comment to the current topic
    location Regular expression specifying the comment location in the target topic. Read carefully the CommentPlugin documentation!  
    mode For compatibility with older versions only, synonymous with type  
    nonotify Set to "on" to disable change notification for target topics "off"
    noform Set to "on" to disable the automatic form that encloses your comment block - remember to insert <form> tags yourself! See CommentPluginExamples#noform for an example. "off"
    nopost Set to "on" to disable insertion of the posted text into the topic. "off"
    remove Set to "on" to remove the comment prompt after the first time it is clicked. "off"
    button Button label text "Add comment"
(See also additional attributes)

Positioning the comment

%COMMENT supports several ways to specify where a comment should be inserted in the target topic. This is referred to as the location of the comment.

Location relative to %COMMENT tag

The default location is the %COMMENT tag itself. For example:

%COMMENT{type="below"}%
will add comments in the current topic, directly below the %COMMENT tag.

Location relative to a TWiki anchor

The target attribute may specify a web, and may also specify an anchor within the target topic; for example,

%COMMENT{type="above" target="%USERSWEB%.PersonalRemarks#InsertHere"}%
This uses a standard TWiki in-topic anchor as the insertion location. See TextFormattingRules for more about TWiki anchors.

Location relative to an arbitrary text string

Getting more sophisticated, you can also specify a regular expression for the target location using the location parameter. The target topic is searched for the regular expression, and the comment inserted relative to the string that the search matched. For example,

%COMMENT{type="above" location="Flights of Fancy"}%
will place comments above the first occurrence of the string Flights of Fancy in the current topic.

Warning of course, if a user's comment contains the string "Flights of Fancy" they may and up changing the location for the next comment! Also, if you use a tag in the location, then you've just inserted another tag in the page that contains the %COMMENT! So be very careful how you specify the RE for location. Note that the RE is matched using perl "multiple line" mode, so ^ and $ match the start of a line and the end of a line respectively.
Also note that you cannot have the text location=" just before the location.

I look forward to someone leveraging this feature to create - for example - threaded conversations using %COMMENT.

If you specify an anchor and a location, the anchor will be ignored.

Default templates

Templates are used to define the "comment style" i.e. how comments appear in the page. The default is to add comments in "Blog like" style using bulleted lists, with the most recent comment at the top, but many other styles are available such as tables or Wiki thread mode comments. It is easy to define your own customer styles as well.

A set of default comment templates are shipped with the plugin - see also CommentPluginTemplates:

Template type Description
top Comments, signed and dated (server time), added at top of the topic (the anchor is ignored)
bottom Comments, signed and dated (server time), added at end of the target topic (the anchor is ignored)
above Comments, signed and dated (server time), added immediately before the target anchor, or the %COMMENT if no anchor is specified
below Comments, signed and dated (server time), added immediately below the target anchor, or the %COMMENT if no anchor is specified
belowthreadmode Comments, signed and dated, added recurse after comment box
threadmode Wiki thread mode comment, signed and dated (server time)
tableprepend Comments, signed and dated (server time), formatted as an HTML table row, added below the anchor (which must be in an HTML <table>)
tableappend Comments, signed and dated (server time), formatted as an HTML table row, added above the anchor (which must be in an HTML <table>)
action Action added to action table directly above comment box (see Plugin Installation Instructions below for important notes)
table Tablerows adding on end
toctalk Talk using TOC adding on end
bookmark Create a list of annotated bookmarks
return Post to a different topic and return

Your local installation may add more template types as well - see Customization, below.

Customization

Customization of the comment plugin requires

To define a comment type, you have to provide two simple template definitions in the template file; one for the prompt box, and one for the generated output. If we have a template type "mytype", these are named PROMPT:mytype and OUTPUT:mytype respectively. See comments.tmpl in the templates directory for examples.

The plugin picks up these template definitions from a standard TWiki template file, templates/comments.tmpl. This allows different templates to be defined for different TWiki skins.

Defining custom templates

By default, templates/comments.tmpl includes the topic CommentPluginTemplate, which contains all the shipped standard templates and in turn includes TWiki.UserCommentsTemplate that can include non-standard customizations.

This allows for several levels of customization:

  1. To override all default templates, everywhere, change comments.tmpl to include a different topic (this customization will be lost next time you upgrade, though).
  2. To add site-wide local template customizations, add them to UserCommentsTemplate (create if it does not exist yet). You can redefine the standard templates here if you want, and your definitions will override the standard definitions.
  3. To override templates on a web-by-web basis, add a topic UserCommentsTemplate to the web (this will replace TWiki.UserCommentsTemplate)
  4. To override templates for a specific skin, add them to TWiki.UserComments<Skin>Template (where <Skin> is the name of the skin with the first letter capitalized, e.g. Pattern)

Per topic custom comment template

You can also define a comment template in a topic, by passing the topic location with a templatetopic parameter. For example:

%COMMENT{type="blogpost" templatetopic="BlogPostCommentTemplate" target="CommentPlugin" button="Add comment" }%

templatetopic accepts topic or web.topic syntax. See an example in CommentPluginExamples#TemplateTopic.

If you use any topic other than UserCommentTemplate, it is critically important that you include this line at the end of your comment template topic:

%TMPL:INCLUDE{"%SYSTEMWEB%.CommentPlugin"}%
Without this line your templates will not be picked up.

ALERT! Templates are picked up by following the standard TWiki rules for locating template files. Note that you can use %TMPL:INCLUDE% to include other files of templates.
ALERT! Note that from TWiki release 4.1.0 leading and trailing whitespace is no longer stripped. This means that when you upgrade to TWiki 4.1.X you may need to remove the first line break in your custom comment templates. See TWikiReleaseNotes04x01 for more information.

Customization example

Provide both a PROMPT and an OUTPUT definition:

%TMPL:DEF{PROMPT:myComment}%%TMPL:P{promptbox}%%TMPL:END%
%TMPL:DEF{OUTPUT:myComment}%%TMPL:P{outputoneliner}%%POS:TOP%
%TMPL:END%

Call your custom comment with:

%COMMENT{type="myComment"}%

The PROMPT template

The PROMPT template defines the contents of an HTML form that is used to capture the comment. This form invokes the comment generator when submitted. Parameters to the comment generator are defined using standard HTML input fields, such as input, textarea and select. The user enters values for these parameters, and these are then available when the OUTPUT template is expanded, in the form of %URLPARAM%s.

Only the input fields of the form need be defined. The plugin automatically generates the <form> and </form> tags, unless you specify noform="on", in which case you have to provide them yourself. Note that you must define a "submit" button if you want the form to work!

Providing attribute values

If an attribute is given to the %COMMENT tag that is not one of the standard attributes, then that attribute is taken as the name of a parameter to be expanded in the PROMPT template. Expressions in the template of the form %param|default% (e.g. %rows|3%, %button|Push me%) are expanded to the values given in the %COMMENT. For example, if the PROMPT template 'example' contains:

<textarea rows=%rows|3% cols="%cols|50%" value="%tval|Rubbish%">
and the %COMMENT tag is:
%COMMENT{type="example" cols="75"}%
then the template will be expanded as
<textarea rows="3" cols="75" value="Rubbish">

Special variables

As well as support for all the usual TWiki variables in templates, the following special variables are supported in the PROMPT definition:

Variable Description
%DISABLED% Set to 'disabled' when you cannot comment (e.g. in preview mode).
%MESSAGE% The text specified by default. This may be overridden by a helpful message when the prompt is DISABLED.

EXPERT Note that when a comment is saved, the TWiki save script is invoked on the target topic, with a number of parameters provided by the comment form. Normally the CommentPlugin will provide these fields in the form, but experts can also provide the fields themselves in order to get finer control over what is submitted, or you might want to define your own HTML forms that do comment submission. The parameters that the CommentPlugin recognises are as follows:

CGI parameter Description
comment_action Must be save to get the CommentPlugin to perform
comment_type Type of the OUTPUT template
comment_index Zero-based index of the %COMMENT in the source topic. Used to place a post relative to an existing %COMMENT.
comment_anchor Anchor taken from the target spec
comment_location As passed to %COMMENT
comment_nonotify As passed to %COMMENT
comment_remove Zero-based index of a %COMMENT to remove from the target topic
comment_nopost As passed to %COMMENT
comment_templatetopic As passed to %COMMENT
Note that comment_location overrides comment_anchor, and both override comment_index. Example, shows an "I Approve" button that adds your approval signature to the end of the topic:
<form method="post" action="%SCRIPTURL{save}%/TWiki/CommentPlugin">
<input type="submit" value="I Approve" />
<input type="hidden" name="comment_action" value="save" />
<input type="hidden" name="comment_type" value="bottom" />
<input type="hidden" name="comment" value="I Approve" />
</form>

Customization example with custom form template

Write a custom form in a topic.

  • In the form set the location of the prompt with %COMMENTPROMPT%; the prompt will be positioned here.
  • In %COMMENT use parameter noform="on"
  • In %COMMENT use parameter templatetopic to point to the topic with the form template

Example form:

%TMPL:DEF{FORM:example}%
<form method="post" action="%SCRIPTURL{save}%/%BASEWEB%/%BASETOPIC%" enctype="application/x-www-form-urlencoded" name="examplecomment" id="examplecomment">
<input type="hidden" name="redirectto" value="%BASEWEB%.%BASETOPIC%" />
%COMMENTPROMPT%
</form>
%TMPL:END%

Example comment:

%COMMENT{noform="on" type="example" templatetopic="Sandbox.CommentPluginTemplateExample" target="CommentPlugin" button="Add comment" }%

The OUTPUT template

The OUTPUT template defines the format for the text that actually gets embedded into the topic. All the usual TWiki variables are available in the PROMPT definition, but note that they get expanded when the comment is inserted in the text, so time, date and username will refer to the time and date when the comment was made, and the user who made it.

There are also four position tags that are used to indicate where the comment should be placed, relative to the location defined in the %COMMENT tag:

%POS:TOP% If present, comments will be inserted at the top of the topic i.e. before any other text
%POS:BOTTOM% If present, comments will be inserted at the end of the topic i.e. after all existing text
%POS:BEFORE% If present, comments will be inserted immediately before the %COMMENT% tag
%POS:AFTER% If present, comments will be inserted immediately after the %COMMENT% tag

Note that these position tags are obviously mutually exclusive. If you define more than one, the result is undefined. If none is present, the default is taken from the plugin setting COMMENTPLUGIN_DEFAULT_TYPE

%COMMENTPROMPT% Use with a custom form. If present, the comment prompt will be positioned here.

All the usual TWikiVariables that can be used in a topic template can also be used in an OUTPUT template. See TWikiVariables for details.

Plugin Settings

Plugin settings are stored as preferences settings. Do not change the settings here, they are here only for illustration purposes showing the default values. Define the settings in Main.TWikiPreferences, in a WebPreferences or in individual topics. For example, to customize the COMMENTPLUGIN_DEFAULT_TYPE setting, add a * Set COMMENTPLUGIN_DEFAULT_TYPE = ... bullet in Main.TWikiPreferences.

  • Name of file in the twiki/templates directory that contains the comment templates. The default 'comments.tmpl' automatically includes user templates from TWiki.CommentPluginTemplate, which in turn includes TWiki.UserCommentsTemplate.
    • Set COMMENTPLUGIN_TEMPLATES = comments

  • Default template type (above or below) :
    • Set COMMENTPLUGIN_DEFAULT_TYPE = above

Plugin Installation Instructions

  • This plugin is pre-installed in TWiki releases. However if you need to upgrade the plugin for any reason:
  • Download the archive file from the Plugin web (see below)
  • Unpack the archive in your twiki installation directory.
    • You may need to correct file permissions
  • Run CommentPlugin_installer to automatically check and install other modules that this module depends on, and enable the plugin.
  • Alternatively,
    • Manually resolve the dependencies listed below. None
  • Use configure to enable the plugin

Note that if you want to use the action template then you must also:

  1. Install the TWiki:Plugins/ActionTrackerPlugin;
  2. Put the CommentPlugin before the ActionTrackerPlugin in the {PluginsOrder} configuration option (in configure)

Plugin Info

  • Set SHORTDESCRIPTION = Quickly post comments to a page without an edit/preview/save cycle.

Plugin Author: TWiki:Main.CrawfordCurrie http://www.c-dot.co.uk inspired by the work of TWiki:Main.DavidWeller and TWiki:Main.PeterMasiar
Copyright: © 2004, TWiki:Main.CrawfordCurrie;
© 2009 TWiki:Main.SopanShewale;
© 2004-2011 TWiki:TWiki.TWikiContributor
License: GPL (GNU General Public License)
Plugin Version: 21517 (2012-01-14)
Change History:  
2011-06-16: TWikibug:Item6754: Fix for action comment template missing %ENDACTION% -- TWiki:Main.JohnRouillard
2011-06-12: TWikibug:Item6725: Change global package variables from "use vars" to "our"; adding NO_PREFS_IN_TOPIC in plugin package -- TWiki:Main.PeterThoeny
2011-03-28: TWikibug:Item6672 - doc improvements: Adding link to HIDE
2010-12-11: TWikibug:Item6530 - doc improvements -- TWiki:Main.ScottGutman
2010-05-16: TWikibug:Item6433 - doc improvements
2010-03-19 TWikibug:Item6404 Use $br in newline parameter for break tag instead of turning off encoding -- TWiki:Main/PeterThoeny
2010-02-27 TWikibug:Item6276 Cannot specify percentBRpercent for newline value -- TWiki:Main/SopanShewale
2009-01-21 TWikibug:Item6163 Fix for Comment Plugin losing data if target anchor is missing -- TWiki:Main/TimotheLitt and TWiki:Main/SopanShewale
03 Aug 2008 The TWiki 4.2.1 release version
11 Apr 2008 TWikibug:Item5518 corrected the template definition for bulletabove
5 Sep 2007 TWikibug:Item3689 corrected location handling TWikibug:Item4181 added VarCOMMENT TWikibug:Item4402 corrected access check
22 Jun 2007 Removed the long-deprecated %TIME (use %GMTIME instead). Minor doc changes
14021 TWikibug:Item3755 Fixed incorrect handling of line terminators when targeting an anchor
13311 Added option to define a comment template in any topic. Pass the topic location with templatetopic (either topic or web.topic). See an example in CommentPluginExamples:templatetopic.
12822 TWikibug:Item3598 minor doc fixes
12750 TWikibug:Item3510 added a note about the changed template spec in TWiki 4.1.0. Code remains unchanged
11358 TWikibug:Item2802 moved SHORTDESCRIPTION to .pm. Coded up TWiki:Main/PankajPant's suggestions as nopost and remove. Added default text for the %COMMENT as requested by TWiki:Main.AndyGlew
11118 TWikibug:Item2322 removed span tag around oneliner bullet output
8788 TWikibug:Item1465 Item1577: reverted 8433 to fix inclusion of correct user templates
8787 TWikibug:Item1573 renamed standard templates topic to avoid naming clash on Windows, where filenames are case-insensitive
8433 TWikibug:Item1465 Fix 'TWiki.' to '%TWIKIWEB%.'; also fixed include 'UserComments' to 'UserCommentsTemplate' (at least that is what the doc suggests)
7427 TWikibug:Item845 removed duplicate date in default comments; stick with server time
7251 TWikibug:Item810 fix for user template inclusion; reorganised templates to make customisation easier
5906 TWikibug:Item143 apache warning from comment plugin when CommentsTmpl.txt not found
5519 CommentPluginOnAnchorsBroken: incorporated JacobEisinger's fix
5518 CommentPluginOnAnchorsBroken: incorporated OlivierBerger's fix
5455 On Niels Kodslo's prompting, removed the global recursion prevention that I believe is no longer needed.
5280 Removed templates, and some minor fixes
5250 Removed newlines from prompt box
4902 Changed to use viewauth. Moved templates into user topics.
4901 Added templates in user webs support
4897 Fixes for disabling during preview; re-enabled old legacy parameters
4889 Chopped down from PeterMasiar version, removing several parameters, savecomment script, changing way templates are done. Major rewrite, atcherly.
4882 Update from PeterMasiar's 2.0 version, plus documentation and small code improvements.
4745 06 Mar 2002 initial commit
Plugin Home: http://TWiki.org/cgi-bin/view/Plugins/CommentPlugin
Feedback: http://TWiki.org/cgi-bin/view/Plugins/CommentPluginDev
Appraisal: http://TWiki.org/cgi-bin/view/Plugins/CommentPluginAppraisal

Related Topics: CommentPluginTemplates, CommentPluginExamples, TWikiPreferences, TWikiPlugins

CommentPlugin examples

CommentPlugin templates

Default

Default comment output 1

-- TWikiContributor - 26 Nov 2006

Default comment output 2

-- TWikiContributor - 26 Nov 2006

 

top

 

bottom

 

above

Above comment output 1

-- TWikiContributor - 26 Nov 2006

Above comment output 2

-- TWikiContributor - 26 Nov 2006

 

below

 

bulletabove

Example with inputsize="20":

  • Bullet above comment output 1
  • Bullet above comment output 2
 

threadmode

Threadmode comment output 1

-- TWikiContributor - 26 Nov 2006

Threadmode comment output 2

-- TWikiContributor - 26 Nov 2006

 

belowthreadmode

 

TWikiContributor - 26 Nov 2006 - 12:09

Belowthreadmode comment output 2

TWikiContributor - 26 Nov 2006 - 12:09

Belowthreadmode comment output 1

tableprepend

 
Tablepreprend comment output 2 TWikiContributor 26 Nov 2006 - 11:03
Tablepreprend comment output 1 TWikiContributor 26 Nov 2006 - 11:02

tableappend

Tableappend comment output 1 TWikiContributor 26 Nov 2006 - 10:38
Tableappend comment output 2 TWikiContributor 26 Nov 2006 - 10:39
 

after

 

action

(requires TWiki:Plugins/ActionTrackerPlugin)

%ACTION{ due="1-Dec-2007" creator="Main.TWikiContributor" uid="000001" state="open" created="26-Nov-2006" who="Main.TWikiContributor" }% <<EOF Action comment output 1 - Created by TWikiContributor, 26 Nov 2006 - 10:58 EOF %ACTION{ due="1-Jan-2008" creator="Main.TWikiContributor" uid="000003" state="open" created="26-Nov-2006" who="Main.TWikiContributor" }% <<EOF Action comment output 2 - Created by TWikiContributor, 26 Nov 2006 - 10:58 EOF

table

1 Dec 2007 TWikiContributor Athens
1 Jan 2008 TWikiContributor Beijing

toctalk

26 Nov 2006 - 00:45 TWikiContributor: Toctalk output summary 1

Toctalk output message 1

26 Nov 2006 - 11:09 TWikiContributor: Toctalk output summary 2

Toctalk output message 2

bookmark

return

Post to a different topic and return to here. In this example comments are written to %COMMENT_TOPIC%. Available with TWiki 4.1.

Comments:

Warning: Can't find topic TWiki.COMMENT_TOPIC


 


noform

Example of a custom form to save a comment to a new topic. When the topic is created the parent will be our Sandbox example topic.

New topic name:
Enter a WikiWord topic name
Topic text:
 

templatetopic

Example of a form definition in a topic. The comment template is located in CommentPluginTemplateExample.

TWikiContributor - 08 Apr 2007:

templatetopic example comment output 1


 
.


Templates for CommentPlugin

See CommentPlugin: Customisation for help.

While this topic can be viewed as a TWiki topic, it is used by the CommentPlugin as a template file - see TWikiTemplates. The important content in here is in the verbatim blocks. The rest of the topic is just comments.

Pointing hand See CommentPluginExamples to view rendered templates.

ALERT! A note on security with the URLPARAM variable: Comments are passed along via URL parameters. They are safely encoded by default to reduce the exposure to cross-site scripting. To preserve user text "as is", and at the cost of security, you can turn off encoding by using encode="off" in the URLPARAM variable. The newline="" parameter of URLPARAM gets encoded with the same encoding as the actual URL parameter. In TWiki 5.0 and later you can specify newline="$br" to add a <br />, regardless of the encoding used.

WARNING: THIS FILE WILL BE OVERWRITTEN WHEN YOU UPGRADE THE COMMENT PLUGIN

Put your local templates into UserCommentsTemplate (create if it does not exist yet). Local templates defined in that topic will override templates defined below.

Template definitions

Templates used in rest of file

Generic prompt box used by other templates
%TMPL:DEF{promptbox}%<div class="commentPlugin commentPluginPromptBox"><table border="0" cellpadding="0" cellspacing="0"><tr valign="middle"><td><textarea %DISABLED% rows="%rows|3%" cols="%cols|70%" name="comment" class="twikiInputField" wrap="soft" onfocus="if(this.value=='%MESSAGE%')this.value=''" onblur="if(this.value=='')this.value='%MESSAGE%'">%MESSAGE%</textarea></td><td>&nbsp;<input %DISABLED% type="submit" value="%button|Add comment%" class="twikiButton" /></td></tr></table></div><!--/commentPlugin-->%TMPL:END%
Short comment, signed and dated
%TMPL:DEF{outputoneliner}%   * %URLPARAM{"comment"}% -- %WIKIUSERNAME% - %GMTIME{"$day $month $year"}%%TMPL:END%

Pointing hand See rendered template Default

User templates

top

Comments, signed and dated, added at top of file
%TMPL:DEF{PROMPT:top}%%TMPL:P{promptbox}%%TMPL:END%

%TMPL:DEF{OUTPUT:top}%%TMPL:P{outputoneliner}%%POS:TOP%
%TMPL:END%

Pointing hand See rendered template top

bottom

Comments, signed and dated, added at end of file
%TMPL:DEF{PROMPT:bottom}%%TMPL:P{promptbox}%%TMPL:END%
%TMPL:DEF{OUTPUT:bottom}%%POS:BOTTOM%%TMPL:P{outputoneliner}%%TMPL:END%

Pointing hand See rendered template bottom

above

Comments, signed and dated, added immediately before anchor
%TMPL:DEF{PROMPT:above}%%TMPL:P{promptbox}%%TMPL:END%
%TMPL:DEF{OUTPUT:above}%%POS:BEFORE%%TMPL:P{OUTPUT:threadmode}%%TMPL:END%

Pointing hand See rendered template above

bulletabove

Bullet item added immediately before anchor. The input field width is passed with variable inputsize, for example:
%COMMENT{type="bulletabove" inputsize="20"}%

%TMPL:DEF{PROMPT:bulletabove}%<input class="twikiInputField" name="bullet_above_item" id="bullet_above_item" type="text" size="%inputsize|40%" value="%URLPARAM{"bullet_above_item"}%" />&nbsp;<input %DISABLED% type="submit" value="%button|Add item%" class="twikiButton" />%TMPL:END%
%TMPL:DEF{OUTPUT:bulletabove}%   * %URLPARAM{"bullet_above_item"}%%POS:BEFORE%
%TMPL:END%

Pointing hand See rendered template bulletabove

threadmode

Wiki thread mode comment, signed and dated
%TMPL:DEF{PROMPT:threadmode}%%TMPL:P{promptbox}%%TMPL:END%
%TMPL:DEF{OUTPUT:threadmode}%%POS:BEFORE%

%URLPARAM{"comment"}%

-- %WIKIUSERNAME% - %DATE%
%TMPL:END%

Pointing hand See rendered template threadmode

belowthreadmode

Comments, signed and dated, added recurse after comment box.

%TMPL:DEF{PROMPT:belowthreadmode}%%TMPL:P{promptbox}%%TMPL:END%
%TMPL:DEF{OUTPUT:belowthreadmode}%%POS:AFTER%
---++++ %WIKIUSERNAME% - %SERVERTIME%

%URLPARAM{"comment"}%

%TMPL:END%

Pointing hand See rendered template belowthreadmode

below

Comments, signed and dated, added immediately below anchor
%TMPL:DEF{PROMPT:below}%%TMPL:P{promptbox}%%TMPL:END%
%TMPL:DEF{OUTPUT:below}%%POS:AFTER%%TMPL:P{outputoneliner}%
%TMPL:END%

Pointing hand See rendered template below

tableprepend

Comments, signed and dated, added at top of table below the anchor/location/COMMENT
%TMPL:DEF{PROMPT:tableprepend}%%TMPL:P{promptbox}%%TMPL:END%
%TMPL:DEF{OUTPUT:tableprepend}%%POS:AFTER%| %URLPARAM{"comment" newline="$br"}% | %WIKIUSERNAME% | %SERVERTIME% |
%TMPL:END%

Pointing hand See rendered template tableprepend

tableappend

Comments, signed and dated, added at end of table above the anchor/location/COMMENT
%TMPL:DEF{PROMPT:tableappend}%%TMPL:P{promptbox}%%TMPL:END%
%TMPL:DEF{OUTPUT:tableappend}%%POS:BEFORE%| %URLPARAM{"comment" newline="$br"}% | %WIKIUSERNAME% | %SERVERTIME% |
%TMPL:END%

Pointing hand See rendered template tableappend

after: Add before the comment box, after the last comment

%TMPL:DEF{PROMPT:after}%%TMPL:P{promptbox}%%TMPL:END%
%TMPL:DEF{OUTPUT:after}%%NOP%%TMPL:P{outputoneliner}%
%POS:BEFORE%%TMPL:END%

Pointing hand See rendered template after

action

Action added to action table directly above comment box (requires TWiki:Plugins/ActionTrackerPlugin)
%TMPL:DEF{PROMPT:action}%

%TABLE{databg="#ffffff" tableborder="0" cellborder="0"}%
|        <label for="action_who">Action for</label>| <input class="twikiInputField" name="action_who" id="action_who" type="text" size="50" value="%URLPARAM{"who"}%" /> |
| <label for="action_due">Due date</label>| <input class="twikiInputField" name="action_due" id="action_due" type="text" size="30" value="%URLPARAM{"due"}%" /> |
|    <label for="action_comment">Comment</label>| <textarea %DISABLED% rows="%rows|3%" cols="%cols|50%" name="action_comment" id="action_comment" class="twikiInputField" wrap="soft" onfocus="if(this.value=='%MESSAGE%')this.value=''" onblur="if(this.value=='')this.value='%MESSAGE%'">%MESSAGE%</textarea> |
|| <input %DISABLED% type="submit" class="twikiButton" value="Add action" /> |
%TMPL:END%
%TMPL:DEF{OUTPUT:action}%%POS:BEFORE%%AC%NOP%TION{who="%URLPARAM{"action_who"}%" due="%URLPARAM{"action_due"}%"}% %URLPARAM{"action_comment" newline="<br />"}%<br />- Created by %WIKIUSERNAME%, %SERVERTIME%
%ENDAC%NOP%TION%
%TMPL:END%

Pointing hand See rendered template action

table

Tablerows adding on end - TWiki:Main/FranzJosefSilli
%TMPL:DEF{PROMPT:table}%
%TABLE{databg="#ffffff" tableborder="0" cellborder="0"}%
|        <label for="comment_date">Date</label>| <input class="twikiInputField" %DISABLED% type="text" size="40" name="comment_date" id="comment_date" /> |
|        <label for="comment_city">City</label>| <input class="twikiInputField" %DISABLED% type="text" size="40" name="comment_city" id="comment_city" value="" /> |
|| <input %DISABLED% type="submit" class="twikiButton" value="%button|Add entry%" /> |
%TMPL:END%
%TMPL:DEF{OUTPUT:table}%%POS:BEFORE%| %URLPARAM{"comment_date"}% | %WIKIUSERNAME% | %URLPARAM{"comment_city"}% |
%TMPL:END%

Pointing hand See rendered template table

toctalk

Talk using TOC adding on end - TWiki:Main/FranzJosefSilli
%TMPL:DEF{PROMPT:toctalk}%
%TABLE{databg="#ffffff" tableborder="0" cellborder="0"}%
|        <label for="comment_summary">Summary</label>| <input class="twikiInputField" %DISABLED% type="text" size="40" name="comment_summary" id="comment_summary" /> |
|        <label for="toctalk_comment_text">Message</label>| <textarea %DISABLED% rows="%rows|3%" cols="%cols|50%" name="toctalk_comment_text" id="toctalk_comment_text" class="twikiInputField" wrap="soft" onfocus="if(this.value=='%MESSAGE%')this.value=''" onblur="if(this.value=='')this.value='%MESSAGE%'">%MESSAGE%</textarea> |
|| <input %DISABLED% type="submit" value="%button|Add%" class="twikiButton" /> |
%TMPL:END%
%TMPL:DEF{OUTPUT:toctalk}%
%POS:BEFORE%---++++ %SERVERTIME% %WIKIUSERNAME%: %URLPARAM{"comment_summary"}%
%POS:BEFORE%%URLPARAM{"toctalk_comment_text" }%
%POS:BEFORE%
%TMPL:END%

Pointing hand See rendered template toctalk

bookmark

Create a list of annotated bookmarks - TWiki:Main/FranzJosefSilli
%TMPL:DEF{PROMPT:bookmark}%
%TABLE{databg="#ffffff" tableborder="0" cellborder="0"}%
|        <label for="comment_url">Url</label>| <input class="twikiInputField" %DISABLED% type="text" size="40" name="comment_url" id="comment_url" value="http://" /> |
| <label for="comment_link">Link label</label>| <input class="twikiInputField" %DISABLED% type="text" size="40" name="comment_link" id="comment_link" /> |
|    <label for="bookmark_comment_text">Comment</label>| <input class="twikiInputField" %DISABLED% type="text" size="40" name="bookmark_comment_text" id="bookmark_comment_text" value="%MESSAGE%" /> |
|| <input %DISABLED% type="submit" value="%button|Add bookmark%" class="twikiButton" /> |
%TMPL:END%
%TMPL:DEF{OUTPUT:bookmark}%%POS:BEFORE%   * [[%URLPARAM{"comment_url" encode="entity"}%][%URLPARAM{"comment_link" encode="entity"}%]] %IF{" '%URLPARAM{"bookmark_comment_text" encode="entity"}%' = '' " then="" else="- "}%%URLPARAM{"bookmark_comment_text" encode="entity"}%
%TMPL:END%

Pointing hand See rendered template bookmark

return

Post to a different topic and return to here. The comment target is set in the PROMPT. In the form below the redirectto is set to the current (including) topic. Available with TWiki 4.1.

%TMPL:DEF{returnpromptbox}%
<input type="hidden" name="redirectto" value="%BASEWEB%.%BASETOPIC%" />
%TMPL:P{promptbox}%
%TMPL:END%
%TMPL:DEF{PROMPT:return}%%TMPL:P{returnpromptbox}%%TMPL:END%
%TMPL:DEF{OUTPUT:return}%%POS:BEFORE%%TMPL:P{OUTPUT:threadmode}%%TMPL:END%

Pointing hand See rendered template return

Include UserComments

Including UserComments:

%TMPL:INCLUDE{"UserComments"}%

DBI Query Plugin

%SHORTDESCRIPTION%

Overview

This plugin is intended to provide TWiki with ability to make complex database requests using DBI Perl module.

Syntax Rules

Syntax:

%DBI_QUERY{"db_identifier" ...}%
SELECT ...
.header
head
.body
%column%
%DBI_SUBQUERY{"name"}%
.footer
footer
%DBI_QUERY%

%DBI_DO{"db_identifier" ...}%
# Some Perl code.
%DBI_DO%

%DBI_DO{"db_identifier" topic="SomeTopic" script="some_script"}%

%DBI_CALL{"subquery"}%

%DBI_CODE{...}%
# Some Perl Code
%DBI_CODE%

DBI_QUERY

Each query consist of two parts: a query statement (SELECT) and output formatting filters. SQL statement starts just after the leading %DBI_QUERY{...}% declaration. The filters are defined by .header, .body, and .footer keywords each starting at the beginning of line. Their meaning shall be obvious from their name:

Declaration Description
.header It is prepended to the query output once.
.body It is repeated for each row of data being fetched from the database.
.footer It is appended to the query output.

Read below on how this plugin works in order to get more detailed explanation of the meaning of each syntax element.

Parameters:

Parameter Description Default Required
"db_identifier" Database ID as defined in the plugin configuration. See plugin configuration section. none required
subquery="name" Defines a subquery which does not produce immediate result but could be used from inside another query none optional
unquoted="col1 col2 ..." List of columns to be left unquoted in the output. Read more in Quoting of Values section. none optional
protected="col1 col2 ..." List of columns to be protected from processing by TWiki engine. none optional

A small note on protected parameter. Say, one has an arbitrary data in a displayed column which could contain any kind of text strings. What happens if a TWiki variable is found in a string? It gets expanded by TWiki, for sure. Adding this columns to the protected list prevents the expansion. Precisely saying, the whole purpose of protection is displaying of data as is, without any modification.

DBI_DO

As a matter of fact, %DBI_DO{...}% is nothing but a Perl CGI script stored withing TWiki. There are three ways to store it:

  1. In place, just between starting %DBI_DO{...}% and ending %DBI_DO%.
  2. In a separate topic which would be then the script on its own.
  3. Several scripts in a topic using %DBI_CODE{...}%.

Parameters:

Parameter Description Default Required
"db_identifier" Database ID as defined in the plugin configuration. See Plugin Installation section. none required
multivalued="par1 par2 ..." Defines HTTP parameters expected to contain several values. These could be, for instance, either values from checkboxes or multiselection lists. none optional
subquery="name" Defines a subquery which does not produce immediate result but could be used from inside another query none optional
topic="SomeTopic" Topic to read script from. none optional
script="name" Specific script defined by its name from several stored in a topic. none optional
name="do_name" Informational parameter which defines in-place stored script name. none optional

DBI_CALL

%DBI_CALL{...}% directly calls a subquery.

Parameters:

Parameter Description Default Required
"subquery" Subquery to call. none required

Moreover, named parameters are transfered to a subquery as if they are columns of a database record. Consider the following example:

%DBI_CALL{"example" uid="12"}%

%DBI_QUERY{"db_identifier" subquery="example"}%
SELECT
    name
  FROM
    Users
  WHERE
    id = %uid%
.header
....
%DBI_QUERY%

ALERT! Read more in Variable Expansion section.

DBI_CODE

%DBI_CODE{...}% is used for keeping several %DBI_DO% scripts within single topic. A script is kept between starting %DBI_CODE{...}% and ending %DBI_CODE%. Output is formatted as a table representing script's name and code.

Parameters:

Parameter Description Default Required
"script_name" Name of the script. Must be unique within topic. none required

TIP Note: Special support is provided for SourceHighlightPlugin.

How it works

DBI_QUERY

This plugin has been written with the idea in mind that table is not the only way to represent database content. Therefore some more flexibility is required in order to format a query result. Yet, what could provide more control over the output than templates keeping it all as simple as possible?

With this view in mind we come to the following procedure:

  1. Every query definition within topic is parsed and stored for further processing. This is done in two major steps:
    1. Query statement is exctracted from the definition.
    2. Every newline within .header, .body, and .footer gets changed with space except for the last ones. They're removed. Whereas newline is needed \n escape sequence must be used. Consequently, \\n is translated into \n.
  2. All queries are processed except for those declared as subqueries:
    1. .header filter is expanded with variable expansion mechanizm and put into the output.
    2. The query statement is expanded using DBIQueryPlugin and TWiki variable expansion mechanisms in the order they are mentioned here.
    3. Database is queried and data is fetched row-by-row. Each row data get quoted and then used for setting DBIQueryPlugin variables. .body filter is expanded using these values.
    4. .footer filter is expanded with DBIQueryPlugin mechanism and put into the output.
    5. Afterwards we let TWiki to mangle with the output (expand variables, pass it through other plugins, whatsoever).

Variable Expansion

The first step of expansion is done by changing every %column% variable found in a text being expanded with corresponding value from the database. Variable names are in fact table column names as they're declared in the SQL statement and returned by DBI module. NAME_lc case conversion performed so that every name is in lowercase. For instance, the following SELECT:

SELECT
    Name,
    PersonalID,
    SomeOtherInfo
  FROM
    PersonData

would provide us with variables %name%, %personalid%, %someotherinfo%.

There are some special cases like SHOW CREATE PROCEDURE query where column names may contain spaces within them. These spaces are changed with undersocre sign making it possible to refer to them as to database columns. I.e. 'Create Procedure' may be referred as %create_procedure%.

The second step is subquery processing. %DBI_SUBQUERY{"subqueryname"}% statements are replaced with output from corresponding subqueries. All currently defined variables are passed to the subquery making it possible to use them for SQL statement, header and footer expansion.

Quoting of Values

Values fetched from database are quoted using CGI::escapeHTML() unless contrary behaviour dictated by unquoted parameter. Then every newline character is changed with TWiki variable %BR%.

Subqueries

Subqueries are processed in same manner as common queries. The only thing which makes them slightly different in behaviour is the fact that they can use column values (variables) from the parent queries. It is also possible to have a chain of subqueries: top_query -> subquery1 -> subquery2 -> ..., in which case all variables from all the calling queries are accessible.

For instance, in the following code:

%DBI_QUERY{...}%
SELECT
    col1, col2
  FROM
    someTable
  WHERE
    col3 = %parent_query_col1%
.body
...
%DBI_QUERY%

we choose only the rows which are somehow related to a row in a parent query. Of course, relatively similar approach would be to use nested SELECT in the parent query SQL statement. Yet, this would be faster. But there are old versions of MySQL where nested SELECT is not supported. And there are situations when some more output formatting is needed. Or one could form header and/or footer using data contained in database.

ALERT! Warning: Column names may overlap with parent queries. In this case parent has influence over child's SQL statement, header and footer definitions; whereas .body uses subquery column names. Take care of this! Best of all avoid this situation by using SQL aliasing:

Parent:

SELECT col1 as parent_col1
....

Subquery:

SELECT col1 as subquery_col1
...

TIP Note: Subqueries could also be called recursively. Although a single query could not be called more than 100 times in a row. This number is presently hardcoded but will become part of plugin settings in future.

DBI_DO

First of all it shall be stated that %DBI_DO% could implement all required functionality. In other words, one could say that %DBI_QUERY% becomes obsolete. This is obvious from the syntax description. But it also implies that %DBI_DO% is:

  • a security risk (see Access Control);
  • too complicated for most queries;

Besides, %DBI_QUERY% hides quite a number of boring implementation details from a user.

So, let's define %DBI_DO% as a last resort method when nothing else could do the job. The most typical use for it would be database editing.

Implementation

As it was stated in syntax section, %DBI_DO% can fetch a script from another topics which would either represent the whole script or contain %DBI_CODE% declarations. In both cases the script is visible on the topic's page. For instance, the following declaration:

%DBI_CODE{"test"}%
if ($varParams{test}) {
    $rc = "This is test.";
} else {
    $rc = "This is for real.";
}
%DBI_CODE%

would output table like this:

Script name test
Script code
if ($varParams{test}) {
    $rc = "This is test.";
} else {
    $rc = "This is for real.";
}

It would look much better with SourceHighlightPlugin:

%DBI_CODE{"test"}%
%CODE{"perl"}%
if ($varParams{test}) {
    $rc = "This is test.";
} else {
    $rc = "This is for real.";
}
%ENDCODE%
%DBI_CODE%

Script name test
Script code
if ($varParams{test}) {
     $rc = "This is test.";
} else {
     $rc = "This is for real.";
}

%DBI_DO% knows about existence of %CODE%/%ENDCODE% and attempts to strip these tags out just after the script has been fetched from a topic. After that Perl code becomes a part of an anonymous sub. Several variables are available to the code:

Variable Description
$dbh Database connection handle.
$cgiQuery A CGI object as returned by TWiki::Func::getCgiQuery().
$varParams Parameters specified in %DBI_DO{...}%. User can put any number of addition parameters there besides those described in syntax section.
$dbRecord Last fetched by %DBI_QUERY% database record or %DBI_CALL% parameters.
%httpParams HTTP parameters as returned by CGI::param() method. Note the multivalued parameter in the syntax section.

Since the sub is executed within plugin's module namespace all internal functions and variables are directly accessible. The most useful of them are described below.

There is one special variable $rc. A value assigned to it is the value returned by sub and put into the output then. In this way one could display a error message or notification or form any kind of TWiki/HTML code.

Useful functions

The following plugin functions could be useful while creating a script:

db_connect($db_identifier)
Useful when connection to another database needed. $db_identifier parameter is database ID as specified in the plugin configuration.
subQuery($subquery, $dbRecord)
Implements %DBI_SUBQUERY% and %DBI_CALL%. $subquery is the name of subquery to be called. $dbRecord has the same meaning as corresponding sub parameter.
expandColumns($text, $dbRecord)
Expands variables within $text as described in DBIQueryPlugin Expansion.
protectValue($text)
Returns $text value modified in a way that prevents it from TWiki processing.
wikiErrMsg(@msg)
Use it for presenting error messages in a uniform way.

Database connection configuration

This plugin relies on the TWiki:Plugins.DatabaseContrib to provide the connection to a DBI database. Please see the contrib for documentation of how to specify the database connection.

Below is an example of the configuration of two database connections, connection1 and test, to be inserted into the DatabaseContrib section of the configure script.

    connection1 => {
        usermap => {
            TWikiAdminGroup => {
                user => 'dbuser1',
                password => 'dbpassword1',
            },
            SpecialGroup => {
                user => 'specialdb',
                password => 'specialpass',
            },
        },
        user => 'guest',
        password => 'guestpass',
        driver => 'mysql',
        database => 'some_db',
        codepage => 'koi8r',
        host => 'your.server.name',
    },
    test => {
        usermap => {
            TWikiAdminGroup => {
                user => 'dbuser2',
                password => 'dbpassword2',
            },
            SomeUser => {
                user => 'someuser',
                password => 'somepassword',
            },
        },
        allow_do => {
            default => [qw(TWikiAdminGroup)],
            'Sandbox.SomeUserSandbox' => [qw(TWikiAdminGroup SpecialGroup)],
        },
        #user => 'nobody',
        #password => 'never',
        driver => 'mysql',
        database => 'test',
        # host => 'localhost',
    }

Access Control

This plugin relies on the TWiki:Plugins.DatabaseContrib for access control.

Additional access protection is implemented for %DBI_DO%, relying on the allow_do key of the configuration specification.

In the example above, for database test, members of the TWikiAdminGroup may perform queries on any topic; users in SpecialGroup may execute %DBI_DO% queries on Sandbox.SomeUserSandbox.

Drawback and problems

Working with a database isn't a simple task, in common. With this plugin I was trying to make it both as simple as possible and flexible same time. Balancing between these two extremes led to some compromises and side effects.

The biggest compromise was usage of Perl inlines for %DBI_DO%. The first approach was to make it working much like %DBI_QUERY%, using sections of declarations. But the more quiestions like:

  • how to check data consistency?
  • how to validate data?
  • how to generate error messages?

and several others of the kind was arising, the more final structure was looking like a new language. So, why developing a new one if Perl is here? But then again, as it was mentioned before, this way is not secure-enough and an administrator must take serious considerations before allowing usage of %DBI_DO% to a user.

The other issue is about plugin execution order. As one can see from MessageBoard example, attached to this topic, usage of other plugins could significally improve control over DBIQueryPlugin output. However, it is not guaranteed that another plugin would not be called in first place causing unpredictable results like unwanted changes in a Perl script.

Considering this issue the decision was made that DBIQueryPlugin must act as a preprocessor. For those who understand, it does all the job in beforeCommonTagsHandler() routine. This approach has three major drawbacks:

  • First of all, it doesn't really follow the guidelines.
  • It breaks common logic of page analysis. Consider the following example:

         %CALC{"$SET(var,1)"}%
         %DBI_QUERY{"..."}%
         SELECT ...
           WHERE
             field = %CALC{"$GET(var)"}%
         %DBI_QUERY%
         

One will not get what would be expected because at the time %CALC{"$GET(var)"}% is executed %CALC{"$SET(var,1)"}% has not been called yet! The only way to have it be done properly is to put the latter just under %DBI_QUERY{...}% line.

  • %INCLUDE{}% would not work because beforeCommonTagsHandler() is not called for included topics.

The last issue was the cause to implement classic plugin handling when it is requested during the inclusion procedure. Possible side effects of this hack are not studied yet and may create some headache.

Plugin Settings

Plugin settings are stored as preferences variables. To reference a plugin setting write %<plugin>_<setting>%, i.e. %DBIQUERYPLUGIN_SHORTDESCRIPTION%

  • One line description, is shown in the TextFormattingRules topic:
    • Set SHORTDESCRIPTION = Make complex database queries using DBI Perl module

  • Debug plugin: (See output in data/debug.txt)
    • Set DEBUG = 0

Plugin Installation Instructions

Note: You do not need to install anything on the browser to use this plugin. The following instructions are for the administrator who installs the plugin on the TWiki server.

  • For an automated installation, run the configure script and follow "Find More Extensions" in the in the Extensions section.

  • Or, follow these manual installation steps:
    • Install TWiki:Plugins.DatabaseContrib
    • Download the ZIP file from the Plugins home (see below).
    • Unzip DBIQueryPlugin.zip in your twiki installation directory. Content:
      File: Description:
      data/TWiki/DBIQueryPlugin.txt Plugin topic
      lib/TWiki/Plugins/DBIQueryPlugin.pm Plugin Perl module
    • Set the ownership of the extracted directories and files to the webserver user.

  • Plugin configuration and testing:
    • Run the configure script and enable the plugin in the Plugins section.
    • Test if the installation was successful

Plugin Info

Plugin Author: TWiki:Main.VadimBelman
Copyright: © 2005-2006 TWiki:Main.VadimBelman
© 2009 TWiki:Main.ThomasWeigert
© 2008-2011 TWiki:TWiki.TWikiContributor
License: GPL (GNU General Public License)
Plugin Version: 2011-03-13
Change History:  
2011-03-13: TWikibug:Item6662: Initial import into SVN; doc fixes; change TWIKIWEB to SYSTEMWEB -- TWiki:Main.DipuDeshmukh
2009-05-20: Use TWiki:Plugins.DatabaseContrib to provide connection services to the database -- TWiki:Main.ThomasWeigert
2009-05-18: Updated to work in TWiki 4.2.4. Corrected the Message Board example -- TWiki:Main.ThomasWeigert
2006-06-03: 1.2: Added 'dsn' and 'init' parameters of configuration file. Character set support for PostgreSQL. No default value for 'allow_do' parameter of configuration file. Support for column names with spaces.
2005-10-17: 1.1
2005-10-13: Initial version
CPAN Dependencies: CPAN:DBI, CPAN:Error
Other Dependencies: TWiki:Plugins.DatabaseContrib
Perl Version: 5.8
TWiki:Plugins/Benchmark: GoodStyle nn%, FormattedSearch nn%, DBIQueryPlugin nn%
Plugin Home: http://TWiki.org/cgi-bin/view/Plugins/DBIQueryPlugin
Feedback: http://TWiki.org/cgi-bin/view/Plugins/DBIQueryPluginDev
Appraisal: http://TWiki.org/cgi-bin/view/Plugins/DBIQueryPluginAppraisal

Related Topics: DatabaseContrib, TWikiPreferences, TWikiPlugins

Database Contrib Package

%SHORTDESCRIPTION%

Summary of Contents

This contrib provides subroutines that come in handy when accessing a SQL database.

  • db_connect connects to a SQL database
  • db_connected verifies that a connection exists for a database
  • db_disconnect disconnects from all databases
  • db_allowed tests for additional access permissions

This contrib is used among others, by TWiki:Plugins.DBIQueryPlugin or TWiki:Plugins.TracQueryPlugin. The hope is that we can consolidate the many different database connection schemes currently in use into this single contrib.

Detailed Documentation

This plugin has its origins in Vadim Belman's excellent TWiki:Plugins.DBIQueryPlugin. Additional capabilities have been migrated from other database connection mechanisms deployed in various TWiki plugins.

This plugin uses the database independent access methods in DBI to facilitate access to the SQL database. In the following $dbh refers to the database handle abstraction of DBI.

db_connect ( $dbname ) -> ( $dbh )

Connects to the database indicated by $dbname. The database can then be queried or updated.

db_connected ( $dbname ) -> ( 0|1 )

Finds the database handle for the indicated database.

db_disconnect ( )

Disconnects from all databases that have been connected to in this session.

db_allowed ( $dbname, $topic )

Verifies that the current user is allowed to perform queries that could change the database destructively. (See Access control below).

Database Definition

The databases that one may connect to are defined through the configure script. The connection information is inserted in the DatabaseContrib section.

Example:
   message_board => {
       user => 'dbuser',
       password => 'dbpasswd',
       driver => 'mysql',
       database => 'message_board',
       codepage => 'utf8',
       allow_do => {
      default => [qw(TWikiAdminGroup)],
      'Sandbox.CommonDiscussion' => [qw(TWikiGuest)],
       },
       host => 'localhost',
   }

This example defines a database message_board and the necessary information to access this database. Additional databases can be added, as a comma-separated list of Perl hash refs.

The following parameters can be used to specify a database. The first level key are the database names used in the above functions. Each database has its own set of parameters defined in the hash.

Key Description Default Required
database Database name on the server. none required
user Default database account name. none optional
password Default database account password. none optional
driver DBI driver used to access the server, (such as mysql, sqlite, oracle).1 none required
dsn Complete dsn string to be used when creating the connection. See your DBD driver documentation.TIP With this key defined both database and driver keys are ignored. none optional
init Initialization command to be sent to the database server just after the connection is initiated. none optional
host DB server hostname. localhost optional
codepage Client-side codepage of this connection.2 none optional
usermap Hash ref mapping TWiki users or groups to database accounts. See Access control below. none optional
allow_do Additional topic-level access control support (see Access control below). default => [qw(TWikiAdminGroup)] optional

1 Only MySQL support has been tested. 2 Only MySQL support provided for this feature. Support for other servers is not implemented yet.

Access Control

The contrib relies on TWiki for authentication and basic access control, and the database server for enforcing security.

Database server-side access control works through mapping TWiki users into database server user accounts by means of the usermap key in the configuration setting (see Database definition above).

  1. Check if TWiki user has an enty in usermap.
  2. Check if TWiki user is a member of a group that has an entry in usermap.
  3. Use user and password keys of the database definition.
  4. If a user was found, connect to the database.

Additional controls are possible at a topic level, if needed. The configuration key allow_do maps individual topics into lists of users or groups with access permission for a query executed from that topic. The key default is used, if a matching key cannot be found for the given topic.

In the example above, members of the TWikiAdminGroup may perform queries onany topic; TWikiGuest is allowed only for topic Sandbox.CommonDiscussion.

Settings

Settings are stored as preferences variables. To reference a setting write %<plugin>_<setting>%, e.g. %DATABASECONTRIB_DEBUG%

  • One line description:
    • Set SHORTDESCRIPTION = Provides subroutines useful in writing plugins that access a SQL database

Installation Instructions

Note: You do not need to install anything on the browser to use this module. The following instructions are for the administrator who installs the module on the TWiki server.

  • For an automated installation, run the configure script and follow "Find More Extensions" in the in the Extensions section.

  • Or, follow these manual installation steps:
    • Download the ZIP file from the Plugins home (see below).
    • Unzip DatabaseContrib.zip in your twiki installation directory. Content:
      File: Description:
      data/TWiki/DatabaseContrib.txt Contrib topic
      lib/TWiki/Contrib/DatabaseContrib.pm Contrib Perl module
      lib/TWiki/Contrib/DatabaseContrib/Config.spec Configuration specification
      lib/TWiki/Configure/Types/TEXT.pm Perl module supporting text areas in configure script
    • Set the ownership of the extracted directories and files to the webserver user.

  • Contrib configuration and testing:
    • Verify access and ownership settings for the new scripts.
    • Edit your .htaccess file to require a valid user for the savesection script (if needed).

Contrib Info

Author: TWiki:Main.ThomasWeigert
Copyright: © 2009 TWiki:Main.ThomasWeigert
© 2009-2011 TWiki:TWiki.TWikiContributor
License: GPL (GNU General Public License)
Plugin Version: 2011-05-14
Change History:  
2011-05-14: TWikibug:Item6701: Small fix in Config.spec and MANIFEST -- TWiki:Main.PeterThoeny
2011-03-13: TWikibug:Item6661: Import into SVN; adding build stuff -- TWiki:Main.DipuDeshmukh
2009-05-20: Initial version
CPAN Dependencies: CPAN:DBI
Other Dependencies: Libraries CPAN:DBI depends on
Perl Version: 5.005
Plugin Home: http://TWiki.org/cgi-bin/view/Plugins/DatabaseContrib
Feedback: http://TWiki.org/cgi-bin/view/Plugins/DatabaseContribDev
Appraisal: http://TWiki.org/cgi-bin/view/Plugins/DatabaseContribAppraisal

Related Topics: TWikiContribs, TWiki:Plugins.DatabasePlugin, TWiki:Plugins.DBIQueryPlugin, TWiki:Plugins.TracQueryPlugin, TWiki:Plugins.PeerReviewPlugin

FAQ:

How do I delete or rename a topic?

Answer:

These two questions are answered together because often when you think you want to delete a page, more often it makes sense to rename the page to contain more context, e.g. rename it to include the date.

You can rename, move and delete topics directly from your browser. Moving lets you transfer a topic from one web to another. The soft delete moves a topic to the special Trash web, where it's hidden but can be "undeleted" with system administrator access.

Click [More topic actions] on the control bar at the bottom of the page you want to change, then choose [Rename/move topic], and make your changes to that screen. There's a link that launches to the ManagingTopics reference page in a pop-up window.

NOTE: The configuration of your site and your own access permissions determine whether you can access these functions.

Note for site administrators: To remove a topic permanently move it to the Trash web, then with file-level access, delete the .txt and .txt,v files manually from /twiki/data/Trash.

Back to: TWikiFAQ

Related Topics: UserDocumentationCategory

FAQ:

How do I delete or rename a file attachment?

Answer:

You can move and delete attachments directly from your browser. Moving lets you transfer an attachment from one topic to another. The soft delete moves an attachment to the special TrashAttachment topic in the Trash web, where it's hidden but can be "undeleted" with system administrator access. Please note that you cannot rename an attachment in the current TWiki release.

Click on [action] on the file in the FileAttachment table, then in the Update attachment screen choose [Move attachment], and make your changes to that screen.

NOTE: The configuration of your site and your own access permissions determine whether you can access these functions.

Note for system administrators: To remove an attachment permanently move it to the Trash.TrashAttachment topic, then with file-level access, delete the file attachment and its ,v repository file manually from twiki/pub/Trash/TrashAttachment.

Back to: TWikiFAQ

Related Topics: UserDocumentationCategory

A List of TWiki Developer Documentation

  • ClassMethod: A ClassMethod is a method that must be called relative to the containing class object...
  • EmptyPlugin: This is an empty plugin. Use it as a template to build your own .TWikiPlugins. This...
  • FileAttribute: Each FileAttachment in a Topic has an attribute string. At present only the hidden...
  • InterwikiPlugin: The InterwikiPlugin links ExternalSite:Page text to external sites based...
  • JQueryPlugin: This plugin contains the latest version of the jQuery JavaScript library....
  • ObjectMethod: An ObjectMethod is a method that must be called relative to a previous constructed...
  • RenderListPlugin: Place a % RENDERLIST{ parameters before any bullet list The lists can...
  • SetGetPlugin: Use % SET{ to store arbitrary text in a named variable, and reuse it with % GET...
  • StaticMethod: A StaticMethod is a method in a package that can be called without reference to an...
  • TWikiAddOns: Add functionality to TWiki with extensions not based on the TWiki scripts. Overview...
  • TWikiContribs: Reusable code that may be used over several plugins and add ons. Overview TWiki...
  • TWikiCss: Listing of CSS class names emitted from TWiki core code and standard plugins. Who...
  • TWikiDocGraphics: This is the TWiki Documentation Graphics library. The graphics can be used in topics...
  • TWikiHistory: New Features and Enhancements of TWiki Release 5.1 Usability Enhancements...
  • TWikiMetaData: Additional topic data, program generated or from TWikiForms, is stored embedded in...
  • TWikiNetSkinPlugin: Helps TWikiNetSkin to render tables and h2 headers. This plugin is only enabled if...
  • TWikiPlugins: Add functionality to TWiki with readily available plugins; create plugins based on...
  • TWikiReferenceManual: Documentation for webmasters, system administrators, project managers, team leaders...
  • TWikiScripts: Programs on the TWiki server performing actions such as rendering, saving and renaming...
  • TWikiSkins: Skins overlay regular templates to give different looks and feels to TWiki screens...
  • TWikiTemplates: Definition of the templates used to render all HTML pages displayed in TWiki Overview...
  • TagMePlugin: Plugin to tag wiki content collectively in order to find content by tags and to get...
  • TwistyPlugin: The TwistyPlugin gives you several options to control the appearance of a twisty...
  • WebLeftBar: 1 Web Users Groups Index Search Changes...
  • WebTopMenu: This topic defines the menu structure of the TWiki web, used by the TopMenuSkin...

Related topics: AdminDocumentationCategory, AdminToolsCategory, CategoryCategory, UserDocumentationCategory, UserToolsCategory

Use the "Minor changes, don't notify" checkbox when saving a page in case you only make a minor change to a topic and you do not want to inform everybody who is on the WebNotify list of the current web of this change.

Note: No new revision is created in case you save the same topic again within a certain time frame (default is one hour). You only need to checkmark the "Minor change, don't notify" checkbox the first time, because subsequent save operations within that period do not notify users.

Note: The initial state of the checkbox can be set to on with the DONTNOTIFYCHECKBOX preferences variable. See TWikiPreferences for more.

Related Topics: UserDocumentationCategory

FAQ:

Why does the topic revision not increase when I edit a topic?

Answer:

The same topic revision will be used when you save a topic again within a certain time frame (one hour by default). This is to prevent unnecessary topic revisions when you do several edit cycles in a row. To force a new revision when saving again within a short time frame, check the "Force new revision" checkbox below the [Save] button.

Note that a new revision is created if another person edits the same topic, regardless of the time.

TWiki administrators can modify the time frame with the {ReplaceIfEditedAgainWithin} configure setting.

Back to: TWikiFAQ

Related Topics: UserDocumentationCategory

Edit Table Plugin

%SHORTDESCRIPTION%

Introduction

Edit TWiki tables in place, using edit fields and drop down boxes, without having to edit the complete topic.

Simply add an [ Edit table ] button to an existing table by writing %EDITTABLE{}% directly above the table. This can be added to tables that are formatted with TablePlugin: add the EDITTABLE variable just above or below the TABLE tag. It can also be used without any TABLE tag.

Customize entry fields by specifying the format: use a text field, a drop down box, a date field, radio buttons or checkboxes.

Multiple tables per topic are editable, but only one at a time can be edited.

Per Table Settings

Add a %EDITTABLE{...}% variable just before an existing table to make it editable, or add the variable anywhere in a topic to start a new table.

  • Supported attributes:
    Attribute Comment Default
    header Specify the header format of a new table like "|*Food*|*Drink*|". Useful to start a table with only a button (no header)
    format The format of one column when editing the table. A cell can be a text input field, or any of these edit field types:
    • Text input field (1 line):
      | text, <size>, <initial value> |
    • Textarea input field:
      | textarea, <rows>x<columns>, <initial value> |
    • Drop down box:
      | select, <size>, <option 1>, <option 2>, etc* |
      * only one item can be selected
    • Radio buttons:
      | radio, <size*>, <option 1>, <option 2>, etc |
      * size indicates the number of buttons per line in edit mode
    • Checkboxes:
      | checkbox, <size*>, <option 1>, <option 2>, etc |
      * size indicates the number of checkboxes per line in edit mode
    • Fixed label:
      | label, 0, <label text> |
    • Row number:
      | row, <offset> |
    • Date:
      | date, <size>, <initial value>, <DHTML date format*> |
      * see Date Field Type
    "text, 16"
    for all cells
    changerows Rows can be added and removed if "on"
    Rows can be added but not removed if "add"
    Rows cannot be added or removed if "off"
    CHANGEROWS
    plugin setting
    quietsave Quiet Save button is shown if "on", hidden if "off" QUIETSAVE
    plugin setting
    include Other topic defining the EDITTABLE parameters. The first %EDITTABLE% in the topic is used. This is useful if you have many topics with the same table format and you want to update the format in one place. (none)
    helptopic Topic name containing help text shown below the table when editing a table. The %STARTINCLUDE% and %STOPINCLUDE% variables can be used in the topic to specify what is shown. (no help text)
    headerislabel Table header cells are read-only (labels) if "on"; header cells can be edited if "off" or "0" "on"
    editbutton Set edit button text, e.g. "Edit this table"; set button image with alt text, e.g. "Edit table, %PUBURL%/%SYSTEMWEB%/TWikiDocGraphics/edittopic.gif"; hide edit button at the end of the table with "hide" (Note: Button is automatically hidden if an edit button is present in a cell) EDITBUTTON
    plugin setting
    buttonrow Set to top to put the edit buttons above the table. bottom
    javascriptinterface Use javascript to directly move and delete row without page refresh. Enable with "on", disable with "off". JAVASCRIPTINTERFACE
    plugin setting

Using TWiki Variables in the Format Parameter

By default, variables in <initial value> (of text input field) and <label text> (of fixed label) get expanded when a new row is added. This can be used for example to add a timestamp to a label. You can escape characters with format tokens if you do not want that.

Any TWiki variable inside a table cell will be preserved. For instance, %TOPIC% will not get expanded to the current topic name.

The format tokens are the same as with FormattedSearch:

Escape: Expands To:
$n or $n() New line. Use $n() if followed by alphanumeric character, e.g. write Foo$n()Bar instead of Foo$nBar
$nop or $nop() Is a "no operation".
$quot Double quote (")
$percnt Percent sign (%)
$dollar Dollar sign ($)

Date Field Type

The date field type allows one to choose a date with a popup calendar. Popup calendar works with all modern browsers. The date picker button is inactive if the browser cannot support the popup calendar or if Javascript is disabled.

The date format can be defined; the default is taken from the {JSCalendarContrib}{format} configure setting. Date specifiers are described in JSCalendarContrib. Example format for ISO date: format="| date, 10, , %Y-%m-%d |".

Edit Table Calendar Example

Per Cell Settings

An individual edit field type can be defined for each table cell. Place an %EDITCELL{ "type, ..." }% variable at the end of the cell content. This is useful to override the per column %EDITTABLE{ format="..." }% settings, or to create tables with key/value rows. All edit field types of the format="..." parameter are supported. For example, to define a text field, type: | cell content %EDITCELL{ "text, 20" }% |

It is also possible to place the edit button inside a cell instead of default location below the table. Type | %EDITCELL{ "editbutton, 1, Edit this table" }% | to show a button, or | %EDITCELL{ "editbutton, 1, Edit table, Image-URL" }% | to show a button image with alternate text.

Note: The %EDITCELL{ }%=variable cannot be used by itself; place an =%EDITTABLE{ }%=variable at the beginning of a table where you want to use =%EDITCELL{ }% variables.

Table Buttons

  • In page view mode:
    • - turn the table into edit mode
  • In edit mode:
    • - save your changes
    • - save your changes without alerting subscribed WebNotify users
    • - add row to the table (if enabled)
    • - remove last row from the table (if enabled)
    • - cancel without saving and release edit lock
    • - Move a row by clicking this button next to the row to be moved, then at a destination.
    • - Deletes the row next to this button.

Examples

Line before table: %EDITTABLE{ format="| row, -1 | text, 20, init | select, 1, one, two, three, four | radio, 3,:-),:-I,:-( | label, 0, %SERVERTIME{"$day $mon $year $hour:$min"}% |" changerows="on" }%

Nr Text field Drop down Mood Timestamp
1 hello table one smile 26 Jun 2002 12:30
2   two frown 27 Jun 2002 12:40

Note: Please do not save this example table! Use TWiki:Sandbox.EditTablePluginTesting if you want to try out this Plugin

If this plugin is installed you will see an [ Edit table ] button above; if you were to click on it (please don't, use TWiki:Sandbox.EditTablePluginTesting for testing) you get this form:

Nr Text field Drop down Mood Timestamp
1 smile indifferent frown 26 Jun 2002 12:30
2 smile indifferent frown 27 Jun 2002 12:40

The following example shows a simple table with key/value rows. The default edit field type for the value column is a text field. This is overloaded by a selector for the Gender, and a date picker for the DOB. This is typically used by TWiki applications where new topics with tables are created based on a template topic.

You type: You get: Table in edit mode:
%TABLE{"headerrows="1"}%
%EDITTABLE{ format="| label | text, 40 |" changerows="off" }%
|*Key*|*Value*|
| Name: | John Smith |
| Gender: | M %EDITCELL{select, 1, , F, M}% |
| DOB: | 1999/12/31 %EDITCELL{date, 10}% |
| City: | New York |
EDITCELL Example in view mode EDITCELL Example in edit mode

Plugin Settings

Plugin settings are stored as preferences variables. To reference a plugin setting write %<plugin>_<setting>%, for example, %EDITTABLEPLUGIN_SHORTDESCRIPTION%

  • One line description, shown in the TextFormattingRules topic:
    • Set SHORTDESCRIPTION = Edit TWiki tables using edit fields, date pickers and drop down boxes

  • Set DEBUG to 1 to get debug messages in data/debug.txt. Default: 0
    • Set DEBUG = 0

  • Set JAVASCRIPTINTERFACE to 1 to be able to directly move and delete row without page refresh. Can be overridden with parameter javascriptinterface.
    • Set JAVASCRIPTINTERFACE = 1

  • Default for change rows flag: on, off, add
    • Set CHANGEROWS = on

  • Default flag for quiet save option: on to show the Quiet Save button, off to hide
    • Set QUIETSAVE = on

  • Default edit button: Specify button text, or specify alternate text, image URL. Note: Texts inside %MAKETEXT{}% are translated into other languages.
    • #Set EDIT_BUTTON = Edit table
    • Set EDIT_BUTTON = Edit this table, edittable.gif
    • Set SAVE_BUTTON = Save table
    • Set QUIET_SAVE_BUTTON = Quiet save
    • Set ADD_ROW_BUTTON = Add row
    • Set DELETE_LAST_ROW_BUTTON = Delete last row
    • Set CANCEL_BUTTON = Cancel

  • Default help texts
    • Set INCLUDED_TOPIC_DOES_NOT_EXIST = Warning: 'include' topic does not exist!

Note: The Plugin uses base settings like date format, language and style from the JSCalendarContrib.

Limitations and Known Issues

  • This Plugin does not support TWiki table formatting like Multi-span cells (e.g. | ... ||) and cell justification (e.g. |  centered  |   right |)
  • There is a performance issue when editing a large table, say, with more then 50 rows
  • You cannot put two %EDITTABLE{}% statements on the same line in the source
  • You can include %-vars now in select values, by quoting them with <nop>, as in %<nop>X% for %X%, say for instance:
    select,1,%<nop>X%,%<nop>Y%

Installation Instructions

Note: This is a pre-installed TWiki plugin. You should not need to install the plugin unless it is for an upgrade.

  • Download the ZIP file from the Plugin web (see below)
  • Unzip EditTablePlugin.zip in your ($TWIKI_ROOT) directory.
  • Alternatively,
    • Manually resolve the dependencies listed below. None
  • The Plugin depends on the viewauth script to authenticate the user. As described in TWikiAccessControl, copy the view script to viewauth (or better, create a symbolic link) and add viewauth to the list of authenticated scripts in the .htaccess file.
  • Visit configure in your TWiki installation, and enable the plugin in the {Plugins} section.
  • Test if the Plugin is correctly installed:
    • Check above example if there is an [ Edit table ] button below the table in above example
    • Click on [ Edit table ], make changes and save the table

Plugin Info

Plugin Author: Arthur Clemens, TWiki:Main.PeterThoeny
Copyright: © 2008 Arthur Clemens;
© 2002-2011 TWiki:Main.PeterThoeny, Twiki, Inc.;
© 2002-2011 TWiki:TWiki.TWikiContributor
License: GPL (GNU General Public License)
Plugin Version: 2011-07-07
Change History:  
2011-07-07: TWikibug:Item6725: Change global package variables from "use vars" to "our"
2010-05-25: 5.1: TWikibug:Item6324 - Fix for editing a table removing EDITCELL from another table - patch by TWiki:Main/NickThorpe
2010-05-16: 5.0: TWikibug:Item6433 - doc improvements; replacing TWIKIWEB with SYSTEMWEB
17 Apr 2009: 4.9.1: Save of table can only be done with http POST method, not GET
01 Nov 2008: 4.9: Arthur Clemens: Fixed rendering of verbatim blocks when editing. Added parameter buttonrow="top" to allow the buttons to be positioned at the top of the table.
26 Sep 2008: 4.8.7: Arthur Clemens: Let empty table initialize more than one column from header parameter
24 Sep 2008: 4.8.6: Arthur Clemens: Fix parsing of header labels
21 Sep 2008: 4.8.5: Arthur Clemens: Fix rendering of TML inside label
03 Aug 2008: 4.8.4: TWiki 4.2.1 release version
19 Jul 2008: 4.8.3: Bugfix release
20 Mar 2008: 4.8: Arthur Clemens: Code refactoring; disabled table sort when editing; removed usage of $percnt to prevent variable expansion (is now done automatically); made Javascript interface aware of headers and footers, and of changerows="off"; improved feedback on row move.
25 Dec 2007: 4.7.1: Arthur Clemens: Added warning if include parameter topic does not exist.
22 Dec 2007: 4.7: Arthur Clemens: Changed handling of escaped variables. To escape TWiki variable, use formatting tokens such as $percnt.
16 Dec 2007: 4.6: Kenneth Lavrsen: The plugin prevents TablePlugin from initsorting the table being edited. This is done by temporarily appending the attribute disableallsort="on" to the TABLE tag of a table being edited. Additionally all header sorting is disabled while editing a table by setting a hidden formfield sort to "off". Disabling sorting while editing is needed now that the EditTablePlugin supports moving rows up and down.
01 Dec 2007: 4.3: Arthur Clemens: added support for TablePlugin headerrows and footerrows; updated edit button
16 Oct 2007: 4.2: Arthur Clemens: refactoring, bug fixes.
07 Oct 2007: 15182: PTh: Added VarEDITTABLE to have it listed in TWikiVariables
15 Mar 2007: Arthur Clemens: Fixed eating of double newlines; icons for Javascript buttons and interface improvements. By default the Javascript interface is turned off, set JAVASCRIPTINTERFACE to use it in edit mode.
05 Mar 2007: Byron Darrah: Added ability to dynamically move and delete rows.
12 Oct 2006: Item2982 Use default date format from JSCalendarContrib
02 Oct 2006: Item2884 Check also for access permission in meta data; proper fix to not warn if oneself has a lock on topic
30 Aug 2006: Item2829 Remove whitespace from select, radio and checkbox items; restored topic lock if $TWiki::Plugins::VERSION < 1.1
29 Jul 2006: Item2684 - Quietly ignore topic edit locks on table edit
21 Jan 2006: TWiki:Main.CrawfordCurrie ported to TWiki-4.0.0, changed to use JSCalendarContrib
16 Sep 2004: Added radio buttons and checkbox controls; escaped "|" pipe symbol found in input fields to preserve tables
01 Aug 2004: Fixed bug where edittable did not work if at the end of a topic
07 Apr 2004: Fixed bug where two tables got updated when you edit and save a table included into a topic containing other edit tables
02 Mar 2004: Default for %EDITCELL{editbutton}% is EDITBUTTON preference
27 Feb 2004: Added QUIETSAVE setting and quietsave parameter; image for Edit button
18 Feb 2004: Doc fixes; allow edit button anywhere in a cell not just at the end of a cell
17 Feb 2004: Added per cell definition of edit field types with %EDITCELL{}% variable; added headerislabel and editbutton parameters
20 Dec 2003: Fixed bug where calendar did not work after adding a row (TWiki:Main/PaulineCheung); added all language files of Mishoo DHTML calendar 0.9.5
13 Dec 2003: Added CHANGEROWS, JSCALENDARDATEFORMAT, JSCALENDARLANGUAGE, JSCALENDAROPTIONS settings
16 Oct 2003: small typo fixed (garbled if ---+ header on top)
15 Oct 2003: new date field type with Javascript calendar - CN
14 Oct 2003: docfix: the documentation page was an old one - CN
13 Oct 2003: bugfix: %-vars in select were resetted to first on add/del row - CN
18 Sep 2003: incompatibility: changed default of changerows to on; support for %-vars, Quiet save for saving without notification; all other fixes in Dev topic integrated - CN
08 Nov 2002: Prevent variable expansion in label text; added escape characters
27 Jun 2002: New helptopic parameter
26 Jun 2002: Support for variables in included EDITTABLE parameters; fixed problem with HTML in cells
21 May 2002: Added fixed label format; new changerows="add" parameter
27 Apr 2002: Fixed bug where text after a double quote in a cell disappeared
18 Apr 2002: Fixed bug where table was breaking when pasting multiple lines into an edit field using Netscape on Unix
08 Apr 2002: Check for change permission and edit lock of topic
05 Apr 2002: Initial version
Dependencies: None
Perl Version: 5.0
TWiki:Plugins/Benchmark: GoodStyle 98%, FormattedSearch 98%, EditTablePlugin 95%
Plugin Home: http://TWiki.org/cgi-bin/view/Plugins/EditTablePlugin
Feedback: http://TWiki.org/cgi-bin/view/Plugins/EditTablePluginDev
Appraisal: http://TWiki.org/cgi-bin/view/Plugins/EditTablePluginAppraisal

Related Topics: VarEDITTABLE, TWikiPreferences, TWikiPlugins

Manage Users: Edit User Account

WikiName of user:   find users

Note: User management is reserved to TWiki administrators.

Related topics: ManagingUsers, QueryUsers, AdminToolsCategory

Empty TWiki Plugin

%SHORTDESCRIPTION%

Introduction

This is an empty plugin. Use it as a template to build your own TWikiPlugins. This plugin does nothing, but is ready to be extended and used.

To create your own plugin:

  • Copy file lib/TWiki/Plugins/EmptyPlugin.pm to <name>Plugin.pm and customize the plugin. Add your own code; remove all handlers you do not plan to use.
  • Create a <name>Plugin documentation topic in the TWiki web. Do so by visiting http://twiki.org/cgi-bin/view/Plugins/PluginPackageHowTo and starting a new topic to get the default plugin topic text (don't save the topic on twiki.org yet). Customize your plugin topic to your needs.
  • Please consider contributing your plugin back to the TWiki community by publishing it in the Plugins web on twiki.org.
  • See details in TWikiPlugins.

Syntax Rules

%EXAMPLEVAR{"..."}%

Parameter Explanation Default
"..." Default parameter. (none)
format="..." Format: ... "$name"

Examples

  • %EXAMPLEVAR{}% expands to: %EXAMPLEVAR{}%

Plugin Installation Instructions

Note: You do not need to install anything on the browser to use this plugin. The following instructions are for the administrator who installs the plugin on the TWiki server.

  • For an automated installation, run the configure script and follow "Find More Extensions" in the in the Extensions section.

  • Or, follow these manual installation steps:
    • Download the ZIP file from the Plugins home (see below).
    • Unzip EmptyPlugin.zip in your twiki installation directory. Content:
      File: Description:
      data/TWiki/EmptyPlugin.txt Plugin topic
      data/TWiki/VarEXAMPLEVAR.txt Variable documentation topic
      lib/TWiki/Plugins/EmptyPlugin.pm Plugin Perl module
      lib/TWiki/Plugins/EmptyPlugin/Config.spec Plugin Config spec
    • Set the ownership of the extracted directories and files to the webserver user.
    • Install the dependencies (if any).

  • Plugin configuration and testing:
    • Run the configure script and enable the plugin in the Plugins section
    • Configure additional plugin settings in the Extensions section if needed.
    • Test if the installation was successful: See example above.

Plugin Info

  • One line description, is shown in the TextFormattingRules topic:
    • Set SHORTDESCRIPTION = Empty Plugin used as a template for new plugins

Plugin Author: TWiki:Main.AndreaSterbini, TWiki:Main.PeterThoeny, TWiki:Main.CrawfordCurrie
Copyright: © 2001-2011, TWiki:TWiki.TWikiContributor
License: GPL (GNU General Public License)
Plugin Version: 21319 (2012-01-14)
Change History:  
2011-05-22: TWikibug:Item6724: Pass text and meta data to registerTagHandler callback -- TWiki:Main.PeterThoeny
2011-05-17: TWikibug:Item6725: Change global package variables from "use vars" to "ours"; doc improvements -- TWiki:Main.PeterThoeny
2011-03-06: TWikibug:Item6656: Add meta data to attachment save handlers
2011-02-08: TWikibug:Item6593: Doc improvements; adding VarEXAMPLEVAR variable documentation
2010-05-08: TWikibug:Item6433: Doc improvements; replacing TWIKIWEB with SYSTEMWEB
2007-05-20: Added renderWikiWordHandler
2006-02-01: Dakar changes
2004-03-21: Added afterSaveHandler
2001-07-14: Changed to plug&play
2001-02-27: Initial version
TWiki Dependency: $TWiki::Plugins::VERSION 1.4
Dependencies: %$DEPENDENCIES
TWiki:Plugins/Benchmark: GoodStyle 99%, FormattedSearch 99%, EmptyPlugin 99%
Plugin Home: http://TWiki.org/cgi-bin/view/Plugins/EmptyPlugin
Feedback: http://TWiki.org/cgi-bin/view/Plugins/EmptyPluginDev
Appraisal: http://TWiki.org/cgi-bin/view/Plugins/EmptyPluginAppraisal

Related Topics: VarEXAMPLEVAR, TWikiPlugins, TWikiFuncDotPm, DeveloperDocumentationCategory, AdminDocumentationCategory, TWikiPreferences

(just an example illustrating how to create a new topic based on a specific template topic. TWikiTemplates has more)

-- TWikiGuest - 2024-04-29

File Attachments

Each topic can have one or more files of any type attached to it by using the Attach screen to upload (or download) files from your local PC. Attachments are stored under revision control: uploads are automatically backed up; all previous versions of a modified file can be retrieved.

What Are Attachments Good For?

File Attachments can be used to archive data, or to create powerful customized groupware solutions, like file sharing and document management systems, and quick Web page authoring.

Document Management System

  • You can use Attachments to store and retrieve documents (in any format, with associated graphics, and other media files); attach documents to specific TWiki topics; collaborate on documents with full revision control; distribute documents on a need-to-know basis using web and topic-level access control; create a central reference library that's easy to share with an user group spread around the world.

File Sharing

  • For file sharing, FileAttachments on a series of topics can be used to quickly create a well-documented, categorized digital download center for all types of files: documents; graphics and other media; drivers and patches; applications; anything you can safely upload!

Web Authoring

  • Through your Web browser, you can easily upload graphics (or sound files, or anything else you want to link to on a page) and place them on a single page, or use them across a web, or site-wide.
    • NOTE: You can also add graphics - any files - directly, typically by FTP upload. This requires FTP access, and may be more convenient if you have a large number of files to load. FTP-ed files can't be managed using browser-based Attachment controls. You can use your browser to create TWikiVariables shortcuts, like this %H% = HELP.

Uploading Files

  • Click on the Attach link at the bottom of the page. The Attach screen lets you browse for a file, add a comment, and upload it. The uploaded file will show up in the File Attachment table.
    • NOTE: The topic must already exist. It is a two step process if you want to attach a file to a non-existing topic; first create the topic, then add the file attachment.
    • Any type of file can be uploaded. Some files that might pose a security risk are renamed, ex: *.php files are renamed to *.php.txt so that no one can place code that would be read in a .php file.
    • The previous upload path is retained for convenience. In case you make some changes to the local file and want to upload it, again you can copy the previous upload path into the Local file field.
    • TWiki can limit the file size. This is defined by the %ATTACHFILESIZELIMIT% variable of the TWikiPreferences, currently set at 150000 KB.
      • ALERT! It's not recommended to upload files greater than a few hundred K through a browser. Large files can be extremely slow-loading, and often time out. Use an FTP site for large file uploads.
  • Automatic attachments:
    • When enabled, all files in a topic's attachment directory are shown as attachments to the topic - even if they were directly copied to the directory and never attached by using an 'Attach' link. This is a convenient way to quickly "attach" files to a topic without uploading them one by one; although at the cost of losing audit trail and version control.
    • To enable this feature, set the {AutoAttachPubFiles} configuration option.
    • NOTE: The automatic attachment feature can only be used by an administrator who has access to the server's file system.

Downloading Files

  • ALERT! NOTE: There is no access control on individual attachments. If you need control over single files, create a separate topic per file and set topic-level access restrictions for each.

Moving Attachment Files

An attachment can be moved between topics.

  • Click Manage on the Attachment to be moved.
  • On the control screen, select the new web and/or topic.
  • Click Move. The attachment and its version history are moved. The original location is stored as topic Meta Data.

Deleting Attachments

Move unwanted Attachments to web Trash, topic TrashAttachment.

Linking to Attached Files

  • Once a file is attached it can be referenced in the topic. Example:
    1. Attach file: Sample.txt
    2. Edit topic and enter: %ATTACHURL%/Sample.txt
    3. Preview: %ATTACHURL%/Sample.txt text appears as: /internal/TWiki/FileAttachment/Sample.txt, a link to the text file.

  • To reference an attachment located in another topic, enter:
    • %PUBURLPATH%/%WEB%/OtherTopic/Sample.txt (if it's within the same web)
    • %PUBURLPATH%/Otherweb/OtherTopic/Sample.txt (if it's in a different web)

  • Attached HTML files and text files can be inlined in a topic. Example:
    1. Attach file: Sample.txt
    2. Edit topic and write text: %INCLUDE{"%ATTACHURL%/Sample.txt"}%
      • Content of attached file is shown inlined.
      • Read more about INCLUDE in TWikiVariables

  • GIF, JPG and PNG images can be attached and shown embedded in a topic. Example:
    1. Attach file: Smile.gif
    2. Edit topic and write text: %ATTACHURL%/Smile.gif
    3. Preview: text appears as /internal/TWiki/FileAttachment/Smile.gif, an image.

File Attachment Contents Table

Files attached to a topic are displayed in a directory table, displayed at the bottom of the page, or optionally, hidden and accessed when you click Attach.

Topic attachments
I Attachment Action Size Date Who Comment
txttxt Sample.txt manage 0.1 K 22 Jul 2000 - 19:37 TWikiContributor Just a sample
gifgif Smile.gif manage 0.1 K 22 Jul 2000 - 19:38 TWikiContributor Smiley face

File Attachment Controls

Clicking on a Manage link takes you to a new page that looks a bit like this (depending on what skin is selected):

Attach new file

Select a new local file to update attachment Sample.txt (UploadingUser)
Upload up to 10000 KB.

Comment

Describe the file so other people know what it is.

Properties

Images will be displayed, for other attachments a link will be created.

Attachments will not be shown in topic view page.

or Cancel

  • The first table is a list of all attachments, including their attributes. An h means the attachment is hidden, it isn't listed when viewing a topic.

  • The second table is all the versions of the attachment. Click on View to see that version. If it's the most recent version, you'll be taken to an URL that always displays the latest version, which is usually what you want.
    • To change the comment on an attachment, enter a new comment and then click Change properties. Note that the comment listed against the specific version will not change, however the comment displayed when viewing the topic does change.
    • To hide/unhide an attachment, enable the Hide file checkbox, then click Change properties.

Known Issues

  • Unlike topics, attachments are not locked during editing. As a workaround, you can change the comment to indicate an attachment file is being worked on - the comment on the specific version isn't lost, it's there when you list all versions of the attachment.
  • Attachments are not secured by default. Anyone can read them if they know the name of the web, topic and attachment. Ask your TWiki administrator if TWiki is configured to secure attachments.

Related Topics: UserDocumentationCategory, TWikiAccessControl

Each FileAttachment in a Topic has an attribute string. At present only the hidden attribute is supported. If the attribute includes h then the attachment is considered to be hidden. It is not listed in the topic, but is displayed when attach page is displayed.

Related Topics: UserDocumentationCategory, DeveloperDocumentationCategory

Normally, if you make subsequent edits within a one hour period (configuration item {ReplaceIfEditedAgainWithin}), TWiki will fold together your changes. This is often the "right thing to do", as it can reduce the visual clutter of the topic history.

The "Force new revision" checkbox is a way to force it to create a separate revision each time you save.

The TWiki.TWikiPreferences variable FORCENEWREVISIONCHECKBOX controls whether this is checked by default or not.

On a related note, you can force every save to be a new revision number by setting {ReplaceIfEditedAgainWithin} to 0.

Related Topics: UserDocumentationCategory, AdminDocumentationCategory

Formatting Tokens

TWiki defines some standard special tokens that can be used to replace characters in some parameters - notably those to FormattedSearch and IfStatements - to defer evaluation of the parameter until later. These special tokens are often called "escapes", because they allow the character to "escape" from its normal meaning.

$n or $n() New line. Use $n() if followed by alphanumeric character, e.g. write Foo$n()Bar instead of Foo$nBar
$nop or $nop() Is a "no operation". This variable gets removed; useful for nested search
$quot or \" Double quote (")
$percnt Percent sign (%)
$dollar Dollar sign ($)
$lt Less than sign (<)
$gt Greater than sign (>)

If you ever find yourself needing to escape an escape, you can use $dollar to escape the leading dollar, thus: $dollarpercnt.

Related topics: FormattedSearch, IfStatements, QuerySearch, TWikiForms

TWiki Formatted Search

Inline search feature allows flexible formatting of search result

The default output format of a %SEARCH{...}% is a table consisting of topic names and topic summaries. Use the format="..." parameter to customize the search result. The format parameter typically defines a bullet or a table row containing variables, such as %SEARCH{ "food" format="| $topic | $summary |" }%. See %SEARCH{...}% for other search parameters, such as separator="".

Syntax

Three parameters can be used to customize a search result:

1. header="..." parameter

Use the header parameter to specify the header of a search result. It should correspond to the format of the format parameter. This parameter is optional.
Example: header="| *Topic:* | *Summary:* |"

Variables that can be used in the header string:

Name: Expands To:
$web Name of the web
$n or $n() New line. Use $n() if followed by alphanumeric character, e.g. write Foo$n()Bar instead of Foo$nBar
$nop or $nop() Is a "no operation". This variable gets removed; useful for nested search
$quot or \" Double quote (")
$percnt Percent sign (%)
$dollar Dollar sign ($)
$lt Less than sign (<)
$gt Greater than sign (>)

2. format="..." parameter

Use the format parameter to specify the format of one search hit.
Example: format="| $topic | $summary |"

Variables that can be used in the format string:

Name: Expands To:
$web Name of the web
$topic Topic name
$topic(20) Topic name, "- " hyphenated each 20 characters
$topic(30, -<br />) Topic name, hyphenated each 30 characters with separator "-<br />"
$topic(40, ...) Topic name, shortened to 40 characters with "..." indication
$parent Name of parent topic; empty if not set
$parent(20) Name of parent topic, same hyphenation/shortening like $topic()
$text Formatted topic text. In case of a multiple="on" search, it is the line found for each search hit.
$locked LOCKED flag (if any)
$date Time stamp of last topic update, e.g. 29 Apr 2024 - 03:49
$isodate Time stamp of last topic update, e.g. 2024-04-29T03:49Z
$rev Number of last topic revision, e.g. 4
$username Login name of last topic update, e.g. jsmith
$wikiname Wiki user name of last topic update, e.g. JohnSmith
$wikiusername Wiki user name of last topic update, like Main.JohnSmith
$createdate Time stamp of topic revision 1
$createusername Login name of topic revision 1, e.g. jsmith
$createwikiname Wiki user name of topic revision 1, e.g. JohnSmith
$createwikiusername Wiki user name of topic revision 1, e.g. Main.JohnSmith
$summary Topic summary, just the plain text, all formatting and line breaks removed; up to 162 characters
$summary(50) Topic summary, up to 50 characters shown
$summary(showvarnames) Topic summary, with %ALLTWIKI{...}% variables shown as ALLTWIKI{...}
$summary(noheader) Topic summary, with leading ---+ headers removed
Note: The tokens can be combined, for example $summary(100, showvarnames, noheader)
$changes Summary of changes between latest rev and previous rev
$changes(n) Summary of changes between latest rev and rev n
$formname The name of the form attached to the topic; empty if none
$formfield(name) The field value of a form field; for example, $formfield(TopicClassification) would get expanded to PublicFAQ. This applies only to topics that have a TWikiForm
$formfield(name, 10) Form field value, "- " hyphenated each 10 characters
$formfield(name, 20, -<br />) Form field value, hyphenated each 20 characters with separator "-<br />"
$formfield(name, 30, ...) Form field value, shortened to 30 characters with "..." indication
$query(query-syntax) Access topic meta data using SQL-like QuerySearch syntax. Example:
$query(attachments.arraysize) returns the number of files attached to the current topic
$query(attachments[name~'*.gif'].size) returns an array with size of all .gif attachments, such as 848, 1425, 923
$query(parent.name) is equivalent to $parent
$pattern(reg-exp) A regular expression pattern to extract some text from a topic (does not search meta data; use $formfield instead). In case of a multiple="on" search, the pattern is applied to the line found in each search hit.
• Specify a RegularExpression that covers the whole text (topic or line), which typically starts with .*, and must end in .*
• Put text you want to keep in parenthesis, like $pattern(.*?(from here.*?to here).*)
• Example: $pattern(.*?\*.*?Email\:\s*([^\n\r]+).*) extracts the e-mail address from a bullet of format * Email: ...
• This example has non-greedy .*? patterns to scan for the first occurance of the Email bullet; use greedy .* patterns to scan for the last occurance
• Limitation: Do not use .*) inside the pattern, e.g. $pattern(.*foo(.*)bar.*) does not work, but $pattern(.*foo(.*?)bar.*) does
• Note: Make sure that the integrity of a web page is not compromised; for example, if you include an HTML table make sure to include everything including the table end tag
$count(reg-exp) Count of number of times a regular expression pattern appears in the text of a topic (does not search meta data). Follows guidelines for use and limitations outlined above under $pattern(reg-exp). Example: $count(.*?(---[+][+][+][+]) .*) counts the number of <H4> headers in a page.
$ntopics Number of topics found in current web. This is the current topic count, not the total number of topics
$nhits Number of hits if multiple="on". Cumulative across all topics in current web. Identical to $ntopics unless multiple="on"
$n or $n() New line. Use $n() if followed by alphanumeric character, e.g. write Foo$n()Bar instead of Foo$nBar
$nop or $nop() Is a "no operation". This variable gets removed; useful for nested search
$quot or \" Double quote (")
$percnt Percent sign (%)
$dollar Dollar sign ($)
$lt Less than sign (<)
$gt Greater than sign (>)

3. footer="..." parameter

Use the footer parameter to specify the footer of a search result. It should correspond to the format of the format parameter. This parameter is optional.
Example: footer="| *Topic* | *Summary* |"

Variables that can be used in the footer string:

Name: Expands To:
$web Name of the web
$ntopics Number of topics found in current web
$nhits Number of hits if multiple="on". Cumulative across all topics in current web. Identical to $ntopics unless multiple="on"
$n or $n() New line. Use $n() if followed by alphanumeric character, e.g. write Foo$n()Bar instead of Foo$nBar
$nop or $nop() Is a "no operation". This variable gets removed; useful for nested search
$quot or \" Double quote (")
$percnt Percent sign (%)
$dollar Dollar sign ($)
$lt Less than sign (<)
$gt Greater than sign (>)

Evaluation order of variables

By default, variables embedded in the format parameter of %SEARCH{}% are evaluated once before the search. This is OK for variables that do not change, such as %SCRIPTURLPATH%. Variables that should be evaluated once per search hit must be escaped. For example, to escape a conditional:
    %IF{ "..." then="..." else="..." }%
write this:
    format="$percntIF{ \"...\" then=\"...\" else=\"...\" }$percnt"

Examples

Here are some samples of formatted searches. The SearchPatternCookbook has other examples, such as creating a picklist of usernames, searching for topic children and more.

Bullet list showing topic name and summary

Write this:

%SEARCH{ "FAQ" scope="topic" nosearch="on" nototal="on" header="   * *Topic: Summary:*" format="   * [[$topic]]: $summary"  footer="   * *Topic: Summary*"  }%

To get this:

  • Topic: Summary:
  • TWikiFAQ: Frequently Asked Questions About TWiki This is a real FAQ, and also a demo of an easily implemented knowledge base solution. To see how it`s done, view the source...
  • TWikiFaqTemplate: FAQ: Answer: Back to: TWikiFAQ
  • TextFormattingFAQ: Text Formatting FAQ This topics lists frequently asked questions on text formatting. Text formatting applies to people who edit TWiki pages in raw edit mode. TextFormattingRules...
  • Topic: Summary

Table showing form field values of topics with a form

In a web where there is a form that contains a TopicClassification field, an OperatingSystem field and an OsVersion field we could write:

| *Topic:* | *OperatingSystem:* | *OsVersion:* |
%SEARCH{ "[T]opicClassification.*?value=\"[P]ublicFAQ\"" scope="text" type="regex" nosearch="on" nototal="on" format="| [[$topic]] | $formfield(OperatingSystem) | $formfield(OsVersion) |" }%

To get this:

Topic: OperatingSystem OsVersion
IncorrectDllVersionW32PTH10DLL OsWin 95/98
WinDoze95Crash OsWin 95

Extract some text from a topic using regular expression

Write this:

%SEARCH{ "__Back to\:__ TWikiFAQ" scope="text" type="regex" nosearch="on" nototal="on" header="TWiki FAQs:" format="   * $pattern(.*?FAQ\:[\n\r]*([^\n\r]+).*) [[$topic][Answer...]]" }%

To get this:

TWiki FAQs:

  • How can I create a simple TWiki Forms based application? Answer...
  • How do I delete or rename a topic? Answer...
  • How do I delete or rename a file attachment? Answer...
  • Why does the topic revision not increase when I edit a topic? Answer...
  • TWiki is distributed under the GPL (GNU General Public License). What is GPL? Answer...
  • I've problems with the WebSearch. There is no Search Result on any inquiry. By clicking the Index topic it's the same problem. Answer...
  • What happens if two of us try to edit the same topic simultaneously? Answer...
  • I would like to install TWiki on my server. Can I get the source? Answer...
  • What does the "T" in TWiki stand for? Answer...
  • So what is this WikiWiki thing exactly? Answer...
  • Everybody can edit any page, this is scary. Doesn't that lead to chaos? Answer...

Nested Search

Search can be nested. For example, search for some topics, then form a new search for each topic found in the first search. The idea is to build the nested search string using a formatted search in the first search.

Here is an example. Let's search for all topics that contain the word "culture" (first search), and let's find out where each topic found is linked from (second search).

  • First search:
    • %SEARCH{ "culture" format="   * $topic is referenced by: (list all references)" nosearch="on" nototal="on" }%
  • Second search. For each hit we want this search:
    • %SEARCH{ "(topic found in first search)" format="$topic" nosearch="on" nototal="on" separator=", " }%
  • Now let's nest the two. We need to escape the second search, e.g. the first search will build a valid second search string. Note that we escape the second search so that it does not get evaluated prematurely by the first search:
    • Use $percnt to escape the leading percent of the second search
    • Use \" to escape the double quotes
    • Use $dollar to escape the $ of $topic
    • Use $nop to escape the }% sequence

Write this:

%SEARCH{ "culture" format="   * $topic is referenced by:$n      * $percntSEARCH{ \"$topic\" format=\"$dollartopic\" nosearch=\"on\" nototal=\"on\" separator=\", \" }$nop%" nosearch="on" nototal="on" }%

To get this:

Note: Nested search can be slow, especially if you nest more then 3 times. Nesting is limited to 16 levels. For each new nesting level you need to "escape the escapes", e.g. write $dollarpercntSEARCH{ for level three, $dollardollarpercntSEARCH{ for level four, etc.

Most recently changed pages

Write this:

%SEARCH{ "\.*" scope="topic" type="regex" nosearch="on" nototal="on" order="modified" reverse="on"  format="| [[$topic]] | $wikiusername  | $date |" limit="7" }%

To get this:

TWikiRegistration GiuliaIafrate 2024-04-08 - 07:41
RedirectPlugin TWikiAdminUser 2023-01-19 - 10:06
VarREDIRECT TWikiAdminUser 2023-01-19 - 10:06
BackupRestoreConsole TWikiAdminUser 2022-12-02 - 09:41
BackupRestorePlugin TWikiAdminUser 2022-12-02 - 09:41
TinyMCEPlugin TWikiAdminUser 2022-12-02 - 09:10
TinyMCEQuickHelp TWikiAdminUser 2022-12-02 - 09:10

Search with conditional output

A regular expression search is flexible, but there are limitations. For example, you cannot show all topics that are up to exactly one week old, or create a report that shows all records with invalid form fields or fields within a certain range, etc. You need some additional logic to format output based on a condition:

  1. Specify a search which returns more hits then you need
  2. For each search hit apply a spreadsheet formula to determine if the hit is needed
  3. If needed, format and output the result
  4. Else supress the search hit

This requires the TWiki:Plugins.SpreadSheetPlugin. The following example shows all topics that are up to exactly one week old.

Write this:

%CALC{$SET(weekold, $TIMEADD($TIME(), -7, day))}%
%SEARCH{ "." scope="topic" type="regex" nosearch="on" nototal="on" order="modified" reverse="on" format="$percntCALC{$IF($TIME($date) < $GET(weekold), <nop>, | [[$topic]] | $wikiusername | $date | $rev |)}$percnt" limit="100" }%

  • The first line sets the weekold variable to the serialized date of exactly one week ago
  • The SEARCH has a deferred CALC. The $percnt makes sure that the CALC gets executed once for each search hit
  • The CALC compares the date of the topic with the weekold date
  • If topic is older, a <nop> is returned, which gets removed at the end of the TWiki rendering process
  • Otherwise, the search hit is formatted and returned

To get this:

Embedding search forms to return a formatted result

Use an HTML form and an embedded formatted search on the same topic. You can link them together with an %URLPARAM{"..."}% variable. Example:

Write this:

<form action="%SCRIPTURLPATH{"view"}%/TWiki/FormattedSearch">
Find Topics: 
<input type="text" name="q" size="32" value="%URLPARAM{"q" encode="entity"}%" />&nbsp;<input type="submit" class="twikiSubmit" value="Search" />
</form>
Result:
%SEARCH{ search="%URLPARAM{"q" encode="quote"}%" type="keyword" format="   * $web.$topic: %BR% $summary" nosearch="on" }%

To get this:

Find Topics:  
Result:

Related Topics: UserDocumentationCategory, SearchHelp, VarSEARCH, SearchPatternCookbook, RegularExpression, QuerySearch

-- Contributors: TWiki:Main.PeterThoeny, TWiki:Main.CrawfordCurrie, TWiki:Main.SopanShewale

FAQ:

TWiki is distributed under the GPL (GNU General Public License). What is GPL?

Answer:

TWiki is distributed under the GNU General Public License, see TWikiDownload. GPL is one of the free software licenses that protects the copyright holder, and at the same time allows users to redistribute the software under the terms of the license. Extract:

  • This program is open source software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
  • This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  • See the GNU General Public License for more details, published at http://www.gnu.org/licenses/gpl-2.0.html

Back to: TWikiFAQ

Related Topics: UserDocumentationCategory

GoodStyle Collaboration Tips

  • TWiki has a very simple text formatting shorthand. In any case, you won't go wrong if you simply:
    • start each line without spaces
    • separate paragraphs with a blank line

  • Run together capitalized words to form WikiWords:
    • WikiWords automatically appear as hyperlinks
    • make up meaningful, reasonably brief Wiki names - it can be a challenge (it'll sharpen you up!)
    • WikiWords has name-creation tips that may help

  • If a discussion is going on:
    • separate each follow-up with a space
    • add your WikiName and the date at the end. Example:
      -- Main.TWikiGuest - 29 Apr 2024
    • OR, by all means, insert your comment where it seems to fit best:
      • you may want to inset it with a bullet and/or set it in italics so it's clear (always sign and date)
    • if you'd like to use an initial, use a link with label. Example:
      -- [[Main.TWikiGuest][ZXQ]] - 29 Apr 2024

  • A good format for a new topic is "dissertation followed by discussion":
    • start with a brief, factual introduction, followed by double horizontal rules
    • let the discussion begin

  • When a discussion dies down and the page becomes static, if you're clear on your course, feel free to refactor mercilessly:
    • fearlessly edit down to capture the key points
    • reduce the noise without losing the facts or the flavor
    • if you merge or delete comments, group credit Contributors: at the end of the page
    • This is how Wiki content matures and grows in value over time.

  • For external site links, you can type URLs directly into the text - http://etcete.ra/... - it'll be clear to anyone where they're headed on click.

  • TWiki is intended for world-wide use, and an internationally understood date format like 2024-09-01 (ISO 8601 date format) or 01 Sep 2024 (RFC 5322 date format) is preferred. It's clearer than the xx/xx/xx format, where a date like 9/1/01 can mean either January or September, depending on the local conventions of the readers. For months, use the first three letters: Jan, Feb, Mar, Apr,...

  • TIP: Check the source when you want to find out how something is formatted: click [Edit] on the lower toolbar. To see earlier versions, click [More topic actions], then check "Raw text format" and click [View revision]. A bit of HTML experience can't hurt, but you'll soon see with TWikiShorthand how far that is from necessary.

Related Topics: UserDocumentationCategory

-- Contributors: TWiki:Main/MikeMannix, TWiki:Main/PeterThoeny

Headlines Plugin

%SHORTDESCRIPTION%

Description

This plugin displays RSS and ATOM feeds from news sites. Use it to build news portals that show headline news.

Note: Syndic8.com ( http://www.syndic8.com/ ) lists many RSS and ATOM feeds.

Syntax Rules

%HEADLINES{"..."}%

Parameter Explanation Default
"..." Source of RSS or ATOM feed; this can be an url (starting with http) or a web.topic location for internal feeds None; is required
href="..." (Alternative to above) N/A
refresh="60" Refresh rate in minutes for caching feed; "0" for no caching Global REFRESH setting
limit="12" Maximum number of items shown Global LIMIT setting
header="..." Header. May include these variables:
- $channeltitle, $title: title of channel (channel.title)
- $channellink, $link: link of channel (channel.link)
- $channeldescription, $description: description (channel.description)
- $channeldate, $date: publication date of the channel (channel.pubDate)
- $rights: copyrights of the channel (channel.copyright)
- $imagetitle: title text for site (image.title)
- $imagelink: link for site (image.link)
- $imageurl: URL of image (image.url)
- $imagedescription: description of image (image.description)
Global HEADER setting
format="..." Format of one item. May include these variables:
- $title: news item title (item.title)
- $link: news item link (item.link)
- $description: news item description (item.description)
- $date: the publication date (item.pubDate, item.date)
- $category: the article category (item.category)
Global FORMAT setting
touch="..." Touch (edit/save) topics if the feed has updates. Specify a comma-space delimited list of TopicNames or Web.TopicNames, such as "%TOPIC%, NewsLetter". Useful to send out newsletter using MailerContrib, showing new feeds since last newsletter. To update feeds, visit topics with feeds in regular intervals (using cron with wget or the like). N/A

The header and format parameters might also use variables rendering the dc, image and content namespace information. Note, that only bits of interest have been implemented so far and those namespaces might not be implemented fully yet.

Rendering the dc namespace

The following variables are extracting the dc namespace info, that could be used in header and format. Note that some of the variables are already used above. This is done by purpose to use different feeds with the same formatting parameters. If there's a conflict the non-dc tags have higher precedence, i.e. a <title> content </title> is preferred over <dc:title> content </dc:title>.

  • $title: channel/article title (dc:title)
  • $creator: channel creator (dc:creator)
  • $subject: subject text; this will also add an image according to the subject hash list, see above (dc:subject)
  • $description: ... (dc:description)
  • $publisher: the channel/article publisher (dc:publisher)
  • $contributor: ... (dc:contributor)
  • $date: ... (dc:date)
  • $type: ... (dc:type)
  • $format: ... (dc:format)
  • $identifier: ... (dc:identifier)
  • $source: ... (dc:source)
  • $language: ... (dc:language)
  • $relation: ... (dc:relation)
  • $coverage: ... (dc: coverage)
  • $rights: ... (dc: rights)

Rendering the image namespace

An image:item is converted into an <img> tag using the following mappings:

  • src: image url (rdf:about attribute of the image.item tag)
  • alt: image title (title)
  • width: image width (image:width)
  • height: image height image:height)

Rendering the content namespace

The variable $content is referring to the <content:encoding> content </content:encoding>.

Examples

Slashdot News

Write

%HEADLINES{ "http://slashdot.org/slashdot.rdf" 
  header="*[[$link][$title]]:* $description" 
  format="$t* [[$link][$title]]"
  limit="4"
}%
to get the latest Slashdot news as a bullet list format:

Business Opportunities Weblog

Write

%HEADLINES{ "http://www.business-opportunities.biz/feed" limit="2" }%

to get the latest postings on the "Business Opportunities" weblog:

Thu, 25 Apr 2024 20:24:31 +0000
The original blog about business opportunities and business ideas for small business entrepreneurs
Thu, 25 Apr 2024 20:24:29 +0000 Carrol Strain
Tue, 23 Apr 2024 17:48:43 +0000 Carrol Strain

Plugin Settings

Plugin settings are stored as preferences settings. Do not change the settings here, they are here only for illustration purposes showing the default values. Define the settings in Main.TWikiPreferences. For example, to customize the HEADLINESPLUGIN_USERAGENTNAME setting, add a * Set HEADLINESPLUGIN_USERAGENTNAME = ... bullet in Main.TWikiPreferences.

  • Refresh rate in minutes for cached feeds. Set to 0 to disable caching:
    • Set HEADLINESPLUGIN_REFRESH = 60

  • Maximum number of items shown:
    • Set HEADLINESPLUGIN_LIMIT = 100

  • Use LWP::UserAgent if set to 1, or fallback to TWiki's internal getUrl() method if set to 0:
    • Set HEADLINESPLUGIN_USELWPUSERAGENT = 1

  • Timeout fetching a feed using the LWP::UserAgent:
    • Set HEADLINESPLUGIN_USERAGENTTIMEOUT = 20

  • Name of user agent:
    • Set HEADLINESPLUGIN_USERAGENTNAME = TWikiHeadlinesPlugin/2011-07-08

  • Default header: (variables are explained in the syntax rules)
      * Set HEADLINESPLUGIN_HEADER = <div class="headlinesChannel"><div class="headlinesLogo"><img src="$imageurl" alt="$imagetitle" border="0" />%BR%</div><div class="headlinesTitle">$n---+!! <a href="$link">$title</a></div><div class="headlinesDate">$date</div><div class="headlinesDescription">$description</div><div class="headlinesRight">$rights</div></div>

  • Default format of one item: (variables are explained in the syntax rules)
      * Set HEADLINESPLUGIN_FORMAT = <div class="headlinesArticle"><div class="headlinesTitle"><a href="$link">$title</a></div>$n<span class="headlinesDate">$date</span> <span class="headlinesCreator"> $creator</span> <span class="headlinesSubject"> $subject </span>$n<div class="headlinesText"> $description</div></div>

  • Values taken from configure: (only supported if CPAN:LWP is installed)
    • $TWiki::cfg{PROXY}{HOST} - proxy host, such as "proxy.example.com";
    • $TWiki::cfg{PROXY}{PORT} - proxy port, such as "8080";
    • $TWiki::cfg{PROXY}{SkipProxyForDomains} - domains excluded from proxy, such as "intra.example.com, bugs.example.com";

Style Sheets

The default HEADER and FORMAT settings use the following styles. See the style.css file defining the default CSS properties (indentation illustrates enclosure).

  • headlinesRss: output of the HeadlinesPlugin (div)
    • headlinesChannel: channel header (div)
      • headlinesLogo: channel logo (div)
      • headlinesTitle: channel title (div)
      • headlinesDate: channel date (div)
      • headlinesDescription: channel description (div)
      • headlinesRight: channel copyright (div)
    • headlinesArticle: one news item (div)
      • headlinesTitle: article title (div)
      • headlinesDate: article date (span)
      • headlinesCreator: author of article (span)
      • headlinesSubject: subect category of the article (span)
      • headlinesText: article text (div)

Plugin Installation Instructions

Note: You do not need to install anything on the browser to use this plugin. The following instructions are for the administrator who installs the plugin on the TWiki server.

  • For an automated installation, run the configure script and follow "Find More Extensions" in the in the Extensions section.

  • Or, follow these manual installation steps:
    • Download the ZIP file from the Plugins home (see below).
    • Unzip HeadlinesPlugin.zip in your twiki installation directory. Content:
      File: Description:
      data/TWiki/HeadlinesPlugin.txt Plugin topic
      pub/TWiki/HeadlinesPlugin/style.css Default CSS
      lib/TWiki/Plugins/HeadlinesPlugin.pm Plugin Perl module
      lib/TWiki/HeadlinesPlugin/Core.pm Plugin core
    • Set the ownership of the extracted directories and files to the webserver user.
    • Make sure the dependencies listed in the table below are resolved.
      NameVersionDescription
      Digest::MD5>=2.33Required. Download from CPAN:Digest::MD5
      LWP::UserAgent>=5.803Optional. Download from CPAN:LWP::UserAgent

  • Plugin configuration and testing:
    • Run the configure script, enable the plugin in the Plugins section
    • Configure the plugin: See plugin settings above.
    • Test if the installation was successful: See example above.

Plugin Info

  • One line description, shown in the TextFormattingRules topic:
    • Set SHORTDESCRIPTION = Show headline news in TWiki pages based on RSS and ATOM news feeds from external sites

Plugin Author: TWiki:Main.PeterThoeny, TWiki:Main.MichaelDaum
Copyright: © 2002-2011 Peter Thoeny, Twiki, Inc.
© 2005-2007 Michael Daum http://wikiring.de
License: GPL (GNU General Public License)
Plugin Version: 2011-07-17
Change History:  
2011-07-17: TWikibug:Item6764: Add VarHEADLINES variable documentation; doc improvements; setting NO_PREFS_IN_TOPIC
2011-07-08: TWikibug:Item6725: Change global package variables from "use vars" to "our"
2010-05-16: TWikibug:Item6433: More doc improvements
2010-04-25: TWikibug:Item6433: Doc fix: Changing TWIKIWEB to SYSTEMWEB
2010-02-27: TWikibug:Item6313: Fixed bug in ATOM feed with <link ...></link> instead of <link ... /> -- Peter Thoeny
2009-09-30: fixed bug in lastBuildDate of feeds affecting touch parameter functionality -- Peter Thoeny
2009-08-29: added touch parameter -- Peter Thoeny
12 Feb 2009: {PROXY}{HOST} supports domain with and without protocol -- Peter Thoeny
06 Feb 2009: added {PROXY}{SkipProxyForDomains} configure setting, added USERAGENTNAME plugin setting -- Peter Thoeny
11 Dec 2008: added {PROXY}{HOST} and {PROXY}{PORT} configure settings -- Peter Thoeny
13 Sep 2007: fixed parsing of content:encoded
23 Jul 2006: improved atom parser; if a posting has no title default to 'Untitled'
26 Apr 2006: added lazy compilation
10 Feb 2006: packaged using the TWiki:Plugins/BuildContrib; minor fixes
03 Feb 2006: off-by-one: limit="n" returned n+1 articles; make FORMAT and HEADER format strings more robust
23 Jan 2006: released v2.00
05 Dec 2005: internal feed urls must be absolute
02 Dec 2005: added web.topic shorthand for internal feeds
29 Nov 2005: fixed CDATA handling
21 Nov 2005: added ATOM support; extended RSS support; added dublin core support; added content support; optionally using LWP to fetch feeds to follow redirections; corrected CPAN dependencies ; recoding special chars from html integer to entity encoding to increase browser compatibility; added css support; use getWorkArea() if available
11 May 2005: TWiki:Main.WillNorris: added DevelopBranch compatability
31 Oct 2004: Fixed taint issue by TWiki:Main.AdrianWeiler; small performance improvement
29 Oct 2004: Fixed issue of external caching if mod_perl or SpeedyCGI is used
02 Aug 2002: Implemented caching of feeds, thanks to TWiki:Main/RobDuarte
11 Jun 2002: Initial version (V1.000)
Perl Version: 5.8
TWiki:Plugins/Benchmark: GoodStyle 100%, FormattedSearch 99.5%, HeadlinesPlugin 94%
Plugin Home: http://TWiki.org/cgi-bin/view/Plugins/HeadlinesPlugin
Feedback: http://TWiki.org/cgi-bin/view/Plugins/HeadlinesPluginDev
Appraisal: http://TWiki.org/cgi-bin/view/Plugins/HeadlinesPluginAppraisal

Related Topics: VarHEADLINES, TWikiPlugins, AdminDocumentationCategory, TWikiPreferences

Hide/Unhide Attachments

You can hide/unhide file attachments in normal topic view.

  • In the FileAttachment table, click on an [action] link,
  • enable the "Hide file" checkbox,
  • then click [Change properties]

Note: All attachments are listed in the attach screen, regardless of the hide file flag.

Related Topics: FileAttachment, UserDocumentationCategory

Hierarchical Navigation

Navigation block that displays the current topic, its parent and children (if any).
This is intended to be included in other topics, for example in a side navigation bar (WebLeftBar).

NOTE: The lookup for parent and children will increase the loading time of your pages.

Usage

Two sections are defined:
  • all
  • children

Displaying the Parent - Current - Children block

%INCLUDE{"%SYSTEMWEB%.HierarchicalNavigation" section="all"}%
generates:

When included in WebLeftBar (using default Pattern skin) this is styled to:

Displaying child topics

*Child topics:*
%INCLUDE{"%SYSTEMWEB%.HierarchicalNavigation" section="children"}%
generates:

Child topics:

When included in WebLeftBar (using default Pattern skin) this is styled to:

%STARTSECTION{name="all"}%<div class="twikiHierarchicalNavigation">
<ul>
%SEARCH{
"parent"
type="query"
topic="%BASETOPIC%"
web="%BASEWEB%"
nonoise="on"
format="<li class='twikiParentTopic'><img src='%ICONURL{parent_gray}%' width='16' height='16' alt='' border='0' /> [[$web.$parent][$parent]]</li>"
}%
<li class='twikiCurrentTopic' style='font-weight:bold;'><nop>%BASETOPIC%</li>%INCLUDE{"HierarchicalNavigation" section="childlist"}%
</ul>
</div><!--/twikiHierarchicalNavigation-->%ENDSECTION{name="all"}%

%STARTSECTION{name="children"}%<div class="twikiHierarchicalNavigation">
<ul>%INCLUDE{"HierarchicalNavigation" section="childlist"}%</ul>
</div><!--/twikiHierarchicalNavigation-->%ENDSECTION{name="children"}%</div>%ENDSECTION{name="children"}%

%STARTSECTION{name="childlist"}%%SEARCH{
"parent.name='%BASETOPIC%'"
web="%BASEWEB%"
type="query"
nonoise="on"
format="<li class='childTopic'><img src='%ICONURL{line_ur_gray}%' width='16' height='16' alt='' border='0' /> [[$web.$topic][$topic]]</li>"
}%%ENDSECTION{name="childlist"}%

IF Statements

The %IF% construct gives TWiki the power to include content in topics based on the value of simple expressions.

%IF{"CONDITION" then="THEN" else="ELSE"}%

In the example above, if CONDITION evaluates to TRUE, then THEN will be included in the topic; otherwise ELSE will be included.

Note that because of the way TWiki evaluates, then whatever is in the THEN and ELSE parameters will already have been expanded by the time the condition is actually evaluated. The standard FormatTokens can be used in the THEN and ELSE parameters when you need to delay evaluation of (for example) a TWiki variable.

The basic syntax of a condition is the same as the syntax used for queries, with operators =, !=, ~, <, >, <=, >=, NOT, AND, OR, (), and functions lc(), uc(), d2n(). In addition, the following special operators are supported:

context True if the current context is set (see below)
allows 'X' allows 'Y' is true if web/topic 'X' exists and allows access mode 'Y' for the current user. Web access rights are only checked if there is no topic called 'X'.
istopic istopic 'X' is true if topic 'X' exists
isweb isweb 'X' is true if web 'X' exists
ingroup 'X' ingroup 'Y' is true if user 'X' is in group 'Y'. 'X' can be a login name or a wikiname.
defined True if a preference variable or url parameter of this name is defined.
isempty True if a preference variable, url parameter or session variable of this name has an empty value. It is equivalent to the expression (defined(x) || $x='')
$ expands a URL parameter or TWikiVariable name. Plugin handlers are not called. Built-in variables and user-defined preferences are supported. You can pass a limited subset of parameters to TWiki variables by enclosing the variable name in single quotes; for example, $ 'VARIABLE{value}'. The 'VARIABLE{value}' string may not contain quotes (' or ").
{X} expands to the value of the configuration variable {X} - for example, {ScriptUrlPath}

Examples:

1. TWiki variable defined or not

%IF{"defined 'WIKINAME'" then="WIKINAME is defined" else="WIKINAME is not defined"}%

2. Compare TWiki variable

You are %IF{ "$ WIKINAME='TWikiGuest' and not defined 'OPEN_DAY'" then="not" }% allowed to
%IF{ "context view" then="view" else="edit"}% this TWiki today.

3. URL parameter

%IF{ "defined 'search'" then="Search: $percntURLPARAM{search}$percnt" else="No search passed in"}%

4. Range test on URL parameter

url param t is %IF{ "0 < $ t and $ t < 1000" then="in" else="out of"}% range.

5. Text comparison of URL parameter

%IF{ "$'URLPARAM{scope}'='text'" then="Plain text search" }% 

6. Configuration item set or not

%IF{ "{AntiSpam}{HideUserDetails}" then="User details are hidden" }%

7. Plugin enabled test

TablePlugin is %IF{ "context TablePluginEnabled" then="enabled" else="disabled" }%.
expands to:
TablePlugin is enabled.

8. Check access permissions

You %IF{"'IfStatements' allows 'change'" then="can" else="cannot"}% change this topic.
You %IF{"'Sandbox.TestTopic' allows 'change'" then="can" else="cannot"}% change Sandbox.TestTopic.
You %IF{"'Sandbox' allows 'change'" then="can" else="cannot"}% change Sandbox web
expands to:
You cannot change this topic. You can change TestTopic. You can change Sandbox web

9. Check topic existance

Topic Sandbox.TestTopic %IF{"istopic 'Sandbox.TestTopic'" then="exists" else="does not exist"}%
Web Sandbox.TestTopic %IF{"isweb 'Sandbox'" then="exists" else="does not exist"}%
expands to:
Topic TestTopic does not exist Web TestTopic exists

10. Group membership

You %IF{"'%USERNAME%' ingroup 'TWikiAdminGroup'" then="are an admin" else="are a normal user"}% 
expands to:
You are a normal user

11. Hide section of text conditionally using CSS visibility

<div style="visibility: %IF{"'%USERNAME%' ingroup 'TWikiAdminGroup'" then="visible" else="hidden"}%">
   * Conditional text enclosed in div tags here...
   * ...can be as long as needed
</div>
Above text is only shown to users who are in the TWikiAdminGroup.

Configuration items are defined in configure. You cannot see the value of a configuration item, you can only see if the item is set or not.

Context identifiers are used in TWiki to label various stages of the rendering process. They are especially useful for skin authors to find out where they are in the rendering process. The following context identifiers are available:

id context
absolute_urls Set if absolute URLs are required
attach in attach script (see TWikiScripts)
authenticated a user is authenticated
body_text when the body text is being processed in a view (useful in plugin handlers)
can_login current environment supports login
changes in changes script (see TWikiScripts)
command_line the running script was run from the command line, and not from CGI
diff in rdiff script (see TWikiScripts)
edit in edit script (see TWikiScripts)
footer_text when the footer text is being processed in a view (useful in plugin handlers)
header_text when the header text is being processed in a view (useful in plugin handlers)
i18n_enabled when user interface I18N support is enabled (i.e., user can choose the language for UI)
inactive if active links such as 'edit' and 'attach' should be disabled
login & logon in login / logon script (see TWikiScripts)
manage in manage script (see TWikiScripts)
mirror if this is a mirror
new_topic if the topic doesn't already exist
oops in oops script (see TWikiScripts)
preview in preview script (see TWikiScripts)
register in register script (see TWikiScripts)
rename in rename script (see TWikiScripts)
resetpasswd in resetpasswd script (see TWikiScripts)
rss if this is an RSS skin rendering
save in save script (see TWikiScripts)
search in search script (see TWikiScripts)
statistics in statistics script (see TWikiScripts)
textareas_hijacked provided for use by editors that highjack textareas, and want to signal this fact. This is used by skins, for example, so they can suppress extra controls when textareas have been hijacked.
upload in upload script (see TWikiScripts)
view in view script (see TWikiScripts)
viewfile in viewfile script (see TWikiScripts)
rest in rest script (see TWikiScripts)
registration_supported registration is supported by the current UserMapper
registration_enabled set if {Register}{EnableNewUserRegistration} is on, and registrationis supported
passwords_modifyable set if the password manager support changing the password / email

In addition there is a context identifier for each enabled plugin; for example, if GallousBreeksPlugin is installed and enabled, then the context ID GallousBreeksPluginEnabled will be set. Other extensions may set additional context identifiers.

The %IF% statement is deliberately kept simple. In particular, note that there is no way to conditionally execute a Set statement. If you need more sophisticated control over formatting, then consider using the SpreadSheetPlugin.

Note also that while the query syntax can be used to access form fields, there are some contexts in which an IF statement may be used where there is no topic context, or the topic context is not what you expected.

Related Topics: QuerySearch, VarIF, VarGET, VarSET, VarSEARCH, FormattedSearch, FormatTokens, SpreadSheetPlugin, TWikiScripts

-- Contributors: TWiki:Main.ArthurClemens, TWiki:Main.CrawfordCurrie, TWiki:Main.PeterThoeny, TWiki:Main.SopanShewale, TWiki:Main.SvenDowideit, TWiki:Main.WillNorris - 2011-04-04

Include Topics and Web Pages Using %INCLUDE{...}% Variable

Use the %INCLUDE{...}% variable to embed the content of another topic or web page inside a TWiki topic. The whole content or only parts of a page can be included. If needed, set a proxy server in TWikiPreferences.

Syntax Example

%INCLUDE{ "page" pattern="reg-exp" rev="2" warn="off" section="clients" PARAMETER1="value" PARAMETER2="Some value"}%

The pattern parameter is optional and allows you to extract some parts of a web page. Specify a RegularExpression that scans from start ('^') to end and contains the text you want to keep in parenthesis, e.g., pattern="^.*?(from here.*?to here).*". You need to make sure that the integrity of a web page is not compromised; for example, if you include an HTML table, make sure to include everything including the table end tag.

The example parameters PARAMETER1 and PARAMETER2 will be defined as a variable within the scope of the included topic. The example parameters shown will result in %PARAMETER1% and %PARAMETER2% being defined within the included topic. A default value can be specified such as %PARAMETER1{ default="..." }% in case the INCLUDE does not specify the parameter. Parametrized includes can be used to define and use macros, which is an alternative to parameterized variables.

VarINCLUDE explains the other parameters.

Note: All text of a topic is included unless it contains a %STARTINCLUDE% and %STOPINCLUDE%, or you specify a section parameter and/or a pattern parameter. A pattern will only search between %STARTINCLUDE% and %STOPINCLUDE%.

Usage Examples

1. Display regression test results in a TWiki page

  <pre>
  %INCLUDE{"http://domain/~qa/v1.1/REDTest.log.txt"}%
  </pre>

2. Display Google's robot.txt file

  %INCLUDE{"http://www.google.com/robots.txt"}%

3. Display the current time in Tokyo in a TWiki page

  • You type:
    • Tokyo: %INCLUDE{"http://TWiki.org/cgi-bin/xtra/tzdate?tz=Asia/Tokyo" pattern="^.*<\!--tzdate:date-->(.*?)<\!--/tzdate:date-->.*"}%
  • You get:
    • Tokyo:
Warning
This site does not allow %INCLUDE% of URLs

4. Create a big document of many included topics

If you create a big document (such as a manual or book) it is better to split up content into topics. You can do that by chapter or sub-section. If needed you can adjust the heading level when you include the chapters into the master document. For example, in the master document you might want to show chapter's H1 heading as H2. Example:

  ---+!! Breadslicer Users Guide
  %TOC{ depth="3" }%
  %INCLUDE{ "UsersGuidePreface"  headingoffset="1" }%
  %INCLUDE{ "UsersGuideChapter1" headingoffset="1" }%
  %INCLUDE{ "UsersGuideChapter2" headingoffset="1" }%
  %INCLUDE{ "UsersGuideChapter3" headingoffset="1" }%
  %INCLUDE{ "UsersGuideChapter4" headingoffset="1" }%
  %INCLUDE{ "UsersGuideAppendix" headingoffset="1" }%
  %INCLUDE{ "UsersGuideIndex"    headingoffset="1" }%

5. Include a topic MyTopic with two parameters

You include the topic with this line

  %INCLUDE{ "MyTopic" BETTER="apples" WORSE="Oranges"}%

An example of a very simple MyTopic could contain

   * I like %BETTER% better than %WORSE%.

The result would be

  • I like apples better than oranges.

TIP Tip: Parameterized variables are a somewhat easier to use alternative to parametrized includes.

6. Alert Box using Parameterized Include

Create a topic called AlertBox with the following content:

-----
%STARTINCLUDE%
<div style="border-color:#FF9933; border-style:solid; border-width:thin; width:85%;  margin: 0 auto">
<table cellpadding="5" width="100%" cellspacing="0" cellpadding="12" border="0">
<tr bgcolor="#FFBB55">
<td valign="top" width="16"><img src="%ICONURL{warning}%" width="16" height="16" align="absmiddle" alt="" border="0"></td>
<td><b> %TITLE{ default="Alert!" }% </b></td>
</tr>
<tr bgcolor="#FFCC66">
<td>&nbsp;</td>
<td> %MESSAGE{ default="Please specify a MESSAGE parameter." }% </td>
</tr>
</table>
</div>
%STOPINCLUDE%
-----

Now you can write %INCLUDE{ "AlertBox" TITLE="Alert" MESSAGE="This a test message" }% to get this:

Alert
  This a test message

The TITLE="" and MESSAGE="" parameters are passed into the include. Using this approach, you can create a library of boxes in the Main web, such as Main.NoteBox, Main.InfoBox.

7. Create a Widget Library

You can create a library of GUI widgets using a topic with named sections:

  1. Create a Main.WidgetLibrary topic
  2. Create widgets in that topic, such as alert boxes, submit forms, queries, etc. Widgets are defined as named sections and may process parameters. For example, above alert box can be a widget enclosed in %STARTSECTION{AlertBox}% ... %ENDSECTION{AlertBox}% (instead of the %STOPINCLUDE% ... %STOPINCLUDE%)
  3. Place a widget in any topic. For example, to use the alert box widget write:
    %INCLUDE{ "Main.WidgetLibrary" section="AlertBox" TITLE="Alert" MESSAGE="The sky is the limit!" }%

In essence, you are building a library of functions with parameters that people can use. Use your imagination, the sky is the limit!

Related Topics: VarINCLUDE, VarSTARTSECTION, VarENDSECTION, UserDocumentationCategory, ParameterizedVariables

-- Contributors: TWiki:Main.PeterThoeny, TWiki:Main.KennethLavrsen

Installed Plugins

Plugins are mainly user-contributed add-ons that enhance and extend TWiki features and capabilities. A limited number of plugins are included in the core TWiki distribution - and any of those can be removed - while the rest are optional, available from TWiki:Plugins.PluginPackage.

Here is a list of the plugins currently installed and enabled on this TWiki site:

  • SpreadSheetPlugin (2018-07-05, $Rev: 30478 (2018-07-16) $): Add spreadsheet calculation like "$SUM( $ABOVE() )" to TWiki tables or anywhere in topic text
  • BackupRestorePlugin (2021-03-19, $Rev: 30914 (2021-03-19) $): Administrator utility to backup, restore and upgrade a TWiki site
  • ColorPickerPlugin (2018-07-05, $Rev: 30442 (2018-07-16) $): Color picker, packaged for use in TWiki forms and TWiki applications
  • CommentPlugin (2018-07-05, $Rev: 30530 (2018-07-16) $): Quickly post comments to a page without an edit/preview/save cycle
  • DatePickerPlugin (2018-07-05, $Rev: 30446 (2018-07-16) $): Pop-up calendar with date picker, for use in TWiki forms, HTML forms and TWiki plugins
  • EditTablePlugin (2018-07-05, $Rev: 30448 (2018-07-16) $): Edit TWiki tables using edit fields, date pickers and drop down boxes
  • HeadlinesPlugin (2018-07-13, $Rev: 30560 (2018-07-16) $): Show headline news in TWiki pages based on RSS and ATOM news feeds from external sites
  • InterwikiPlugin (2018-07-05, $Rev: 30454 (2018-07-16) $): Write ExternalSite:Page to link to a page on an external site based on aliases defined in a rules topic
  • JQueryPlugin (2018-07-05, $Rev: 30456 (2018-07-16) $): jQuery JavaScript library for TWiki
  • PreferencesPlugin (2018-07-05, $Rev: 30528 (2018-07-16) $): Allows editing of preferences using fields predefined in a form
  • RedirectPlugin (2015-12-02, $Rev: 29697 (2015-12-03) $): Create a redirect to another topic or website
  • SetGetPlugin (2018-07-05, $Rev: 30472 (2018-07-16) $): Set and get variables and JSON objects in topics, optionally persistently across topic views
  • SlideShowPlugin (2018-07-05, $Rev: 30474 (2018-07-16) $): Create web based presentations based on topics with headings.
  • SmiliesPlugin (2018-07-05, $Rev: 30476 (2018-07-16) $): Render smilies as icons, like  :-) for smile or  :eek: for eek!
  • TWikiSheetPlugin (2018-07-15, $Rev: 30604 (2018-07-16) $): Add TWiki Sheet spreadsheet functionality to TWiki tables
  • TablePlugin (2018-07-05, $Rev: 30480 (2018-07-16) $): Control attributes of tables and sorting of table columns
  • TagMePlugin (2018-07-05, $Rev: 30482 (2018-07-16) $): Tag wiki content collectively or authoritatively to find content by keywords
  • TinyMCEPlugin (2021-06-09, $Rev: 31045 (2021-06-09) $): Integration of the Tiny MCE WYSIWYG Editor
  • TwistyPlugin (2018-07-06, $Rev: 30497 (2018-07-16) $): Twisty section JavaScript library to open/close content dynamically
  • WatchlistPlugin (2018-07-10, $Rev: 30536 (2018-07-16) $): Watch topics of interest and get notified of changes by e-mail
  • WysiwygPlugin (2018-07-06, $Rev: 30528 (2018-07-16) $): Translator framework for WYSIWYG editors

Administrators can enable and disable plugins using Wrench, tools configure.

All Contrib Modules

This list includs Plugins, some some of which may be disabed in configure, or due to other reasons. See TWikiSkinBrowser for an overview of the installed Skins.

Plugin Diagnostics

PluginErrors
SpreadSheetPlugin none
BackupRestorePlugin none
ColorPickerPlugin none
CommentPlugin none
DatePickerPlugin none
EditTablePlugin none
HeadlinesPlugin none
InterwikiPlugin none
JQueryPlugin none
PreferencesPlugin none
RedirectPlugin none
SetGetPlugin none
SlideShowPlugin none
SmiliesPlugin none
TWikiSheetPlugin none
TablePlugin none
TagMePlugin none
TinyMCEPlugin none
TwistyPlugin none
WatchlistPlugin none
WysiwygPlugin none
HandlerPlugins
afterEditHandlerWysiwygPlugin
afterRenameHandlerTagMePlugin
WatchlistPlugin
afterSaveHandlerTagMePlugin
WatchlistPlugin
beforeCommonTagsHandlerEditTablePlugin
PreferencesPlugin
TWikiSheetPlugin
TwistyPlugin
WysiwygPlugin
beforeEditHandlerTinyMCEPlugin
WysiwygPlugin
beforeMergeHandlerWysiwygPlugin
beforeSaveHandlerCommentPlugin
WatchlistPlugin
WysiwygPlugin
commonTagsHandlerSpreadSheetPlugin
BackupRestorePlugin
CommentPlugin
EditTablePlugin
JQueryPlugin
SlideShowPlugin
SmiliesPlugin
TWikiSheetPlugin
initPluginSpreadSheetPlugin
BackupRestorePlugin
ColorPickerPlugin
CommentPlugin
DatePickerPlugin
EditTablePlugin
HeadlinesPlugin
InterwikiPlugin
JQueryPlugin
PreferencesPlugin
RedirectPlugin
SetGetPlugin
SlideShowPlugin
SmiliesPlugin
TWikiSheetPlugin
TablePlugin
TagMePlugin
TinyMCEPlugin
TwistyPlugin
WatchlistPlugin
WysiwygPlugin
modifyHeaderHandlerWysiwygPlugin
postRenderingHandlerPreferencesPlugin
WysiwygPlugin
preRenderingHandlerInterwikiPlugin
SmiliesPlugin
TablePlugin
21 plugins

Note: The diagnostics are provided by the %FAILEDPLUGINS% variable

Related Topics: TWikiPlugins, TWikiPreferences, AdminDocumentationCategory, AdminToolsCategory, TWikiSkinBrowser

Instant TWiki Site Enhancements

These quick enhancements are aimed at improving and customising your TWiki. New TWiki site administrators are especially encouraged to review this document for ideas before deploying a new TWikiSite. The metaphor of building a house is useful. The listed enhancements are some of the details possible when moving into a new office or home. These small changes can make a big differences for user satisfaction at your site. All modifications can be done through your Web browser, and they don't take more then in a couple of minutes. No system administration expertise is required. Some of these enhancements are also mentioned in the reference manual and other topics.

Many of these tips are based on setting some special TWikiVariables.

PICK We recommend implementing at least some of these enhancements right after installation to get a taste for what is possible. Some of these tips and enhancements should be implemented before or during initial roll-out.

This may spark your imagination to really customize your site so that it's optimal for your users. Slightly more advanced customization tips are listed in TWiki:TWiki.TWikiAdminCookBook.


Tips using TWiki Variables

TWikiVariables are a great resource to customize your site. You need to know the variable name and decide where to put it.

Change Colors of Page Header/Footer

Incredibly obvious, maybe, but some TWiki site admins don't get around to changing the default web colors right off, whether they like them or not. Simply changing the defaults will make a huge difference in the overall look.

What we are doing

We want to set variable WEBBGCOLOR in topic WebPreferences to one of the StandardColors. WebPreferences is, as you can guess, a topic which holds all kind of preference setting for each TWiki Web{*}. Each web has its own WebPreferences, and you can set them differently for each web.

How to do it

  1. Pick color code from company or product references, the StandardColors table (recommended for 8-bit client compatibility), or some other color reference.
  2. Go to WebPreferences in each web, and edit the topic.
  3. Set your preferred WEBBGCOLOR preferences variable, and save the topic.
  4. ALERT! Add a new line immediately after the color code. If there is (invisible) space after the color code, the page header might get strange colors (e.g. black).

It's just as easy to refine later on, so you're not locked in, just looking better.

Set Page Background Color

Without getting into the TWikiTemplates system yet, you can easily edit the view.tmpl (in the templates directory). In the HTML at the top, the body tag has the page background hardcoded to white bgcolor="#ffffff". You can change that color value to new variable. First, define a new preferences variable in the site-level Main.TWikiPreferences, e.g. * Set =PAGEBGCOLOR = #d0d0d0, then edit the view.tmpl template file and change bgcolor="#ffffff" to bgcolor="%PAGEBGCOLOR%". If you want, you can set the page background color individually per web, simple add a * Set =PAGEBGCOLOR = #d0d0d0 bullet to the WebPreferences to overload the site-level preferences. (Without font color control, you'll have to stick to light colors.)

Titles-Only Topic List - WebTopicList

WebTopicList is a good first navigation tool for new users, a fast-loading linked list (page titles only) of a web's topics is a quick and easy way see what's available. By default, slower, but more powerful WebIndex is used.

Without explaining what WEBTOPICLIST is, just try it:

  1. Go to WebPreferences in each web, and edit the topic.
  2. In WEBTOPICLIST variable, replace WebIndex with WebTopicList, and save.

Simple way to create colored text and graphics

This should be enabled, see the "Miscellaneous Settings" in the TWikiPreferences, . If not, look at TWiki:TWiki/TWikiPreferences. Look for variables RED, BLUE etc (which define HTML tag FONT). To copy/paste the variables defining the colors you need to see the source text, but Edit is disabled. Instead, go to More and view the topic in raw format.

EZ Graphic Icons to Highlight Text

Icons can do a lot to enhance scannability of topics. For instance, on HELP pages, most people tend to jump around looking for answers rather than reading through - icons help point out the most important bits.

TWikiDocGraphics has a whole collection of ready icon images. You can use these images in any topic by referring to their name. For example, TWikiDocGraphics has an image attachment called days.gif. To show this image in a topic, write %ICON{"days"}% to get Days, Calendar.

Creating image variables

You may find it easier to write shorthand graphic notation. You can create your own image variables by defining them in a preference topic (most likely Main.TWikiPreferences.)

A variable name may be one letter, like Y, or may be longer like HELP, WARN etc. You can also add your own images, e.g. a NEW, or a ASK to ask question.

For instance, if we want to write %DOWN% instead of %ICON{"arrowbdown"}%, define the new variable like this:

   * Set DOWN = %ICON{"arrowbdown"}%
Or if you have a custom image to use, attach this to Main.TWikiPreferences and write:
   * Set DOWN = <img src="https://wiki.ivoa.net/internal/TWiki/InstantEnhancements/my_image.gif" border="0" alt="DOWN" width="16" height="16" />

Most images in TWikiDocGraphics are 16 x 16 pixels.

  • Related: There are other approaches for creating more extensive TWiki icon libraries. This is a simply and quick way to get started. See TWikiDocGraphics for more info.

Use TOC variable to create table of content

TOC is Table-Of-Content, generated automagically from headers (defined like that: ---++ , see TWikiShorthand).

For example, you may want to put all your custom variables in Main.TWikiPreferences right on top of the page, and generate table of contents, like:

  • Preferences for easy creating nice pages
    • Graphics icons in text
    • Colored text
  • System Preferences
    • Contents of page header and footer
    • User interface defaults
    • Email
    • Plugins
    • Notes

Non-admin users wil be interested only in first part, non-system preferences.


Personal Productivity - Tools and Tips for Working Faster

Although this area applies to all TWiki setups, the initial focus is on TWiki site managers working on a Linux/Apache TWiki site, from a Windows local PC. The assumption being: if you're working with Linux as your desktop, you're probably a programmer or system admin and have these basics handled!

Use your favorite text editor for major edits

When you have a fair bit of TWiki formatting work - for example, compiling new info pages from various cut'n'paste sources, editing multiple TWiki topics or contributed material - it's often easier to use a real TextEditor instead of the browser's text edit box. There are several methods for doing this. For Windows, there are several well-recommended text editors.

Windows Example: TextPad is a low-cost, top flight Windows program, with an extended trial period. You can download from a well-stocked library of user-contributed macros, dictionaries, and syntax and clip files. You can also easily create a TWiki clip collection that allows you to format text with TWiki code: select a text string and click for bold, italic, links, bullet lists - just like a regular HTML editor - and also insert blocks of TWiki code, use simple or regex search and replace, more.

Copy & Paste: Using the web window this can work very well. System differences may present difficulties with this method but it is simple and reliable in most cases.

Browser Integration: Some web browsers can be configured to automatically use an external editor. See your browser documentation for details. Such a configuration and a small tool for Linux is described in an example on TWiki.org. TWiki:Codev/EditDaemonWithGVimIntegration

Alternate Browser: While your main browser might not have the features for TWiki topic editing, another one might.

  • An example on the Linux platform is the w3m pager/browser for Linux. This is a text based version similar to lynx but it includes text editor features and a configurable command set to act like lynx if you are more accustomed to it.

Ready to use SEARCH

Personal directory of topics you're involved in

Here's how you can create your own personal directory of topics you've contributed to recently. Copy the text below (between Start Copy and End Copy) and paste it into your personal page (TWikiGuest). You can add other webs to search by duplicating one of the web subsections and editing the string {web ="webname"} in the search parameters to refer to the specific web you want to search. This script would also work for a group.

Start Copy

__Here's a list of topics I've been involved in recently:__

---++++ Codev

%SEARCH{ "InstantEnhancements" web="Codev" scope="text" nosearch="on" nosummary="on" noheader="on" nototal="on" order="modified" reverse="on" limit="20"}%
---++++ Support

%SEARCH{ "InstantEnhancements" web="Support" scope="text" nosearch="on" nosummary="on" noheader="on" nototal="on" order="modified" reverse="on" limit="20"}%

---++++ TWiki

%SEARCH{ "InstantEnhancements" web="TWiki" scope="text" nosearch="on" nosummary="on" noheader="on" nototal="on" order="modified" reverse="on" limit="10"}%

End Copy

The SEARCH variable has many more formatting options, see TWikiVariables.

Recently changed pages

Here are the last 15 changed pages, formatted into a neat table.

<table>
%SEARCH{ "\.*" scope="topic" type="regex" nosearch="on" nototal="on" order="modified" reverse="on"  format="<tr><td>  [[$topic][$topic]] </td><td>  $wikiusername  </td><td> $date  </td></tr>" limit="15" }%
</table>


Hidden Edit Lock for Individual Topics

When you're creating main gateway pages, you may want to temporarily (or permanently) restrict editing to yourself or a limited group of people. You can do this with a Preference setting that includes one or more users and groups. Only auhorized users will be able to use Edit.

  • Example: Set ALLOWTOPICCHANGE = Main.UserName, Main.GroupName
  • TIP To hide the setting: Use HTML comment tags - put <!-- on the line _above the setting, and --> on the line below.


Change the Default Logo

If you want to change the logo per TWiki web, simply attach a new logo.gif to the web's WebPreferences, and change the logo's filename by overriding the name using WEBLOGONAME in WebPreferences:

  • Set WEBLOGONAME = filename.gif

Other cusomtisations are possible using WEBLOGOIMG, WEBLOGOURL, and WEBLOGOALT (they mirror the WIKILOGO* TWiki variables, but are applied to each web, rather than to the %WIKITOOLNAME%-based references)

If you'd like to have the same customised logo for all the webs, make these changes in TWikiPreferences instead of each web's WebPreferences, e.g.,

  • Set WEBLOGOIMG = %PUBURLPATH%/Main/WebPreferences/mylogo.gif


Customize Topic Classification Forms

With a simple one or two-line default topic form available for every topic - in Edit mode, click the [Add] button, and select the form if it isn't already enabled. Then, click the title to get to the actual form, [Edit], and carefully change values, probably basic page classifications. You'll get some increased value, and hands-on experience with TWikiForms, without having to read up about them first. ALERT! (add the corresponding search per category - copy a default and change)


Add Your Favorite JavaScript Features

You're no doubt familiar or better with HTML, JS, and "webmastering". Without getting into the TWikiTemplates system yet, you can easily edit the view.pattern.tmpl (if you are using default pattern skin) (in the templates directory) for some dramatic effects. The top of the template is mostly regular HTML with some variables. Open up some space in the <head> area, and you can drop in reliable JavaScripts - a pop-up window script, for example - or tag it as an external script.

  • TIP Obviously, you can do the same - place a link to an external stylesheet as well. If you set values for standard HTML tags, you can control a good deal of the type size, style and color with out adding CSS tags. example

ALERT! Depending on what you load up, you may change the overall cross-browser compatibility - however be careful that your site does not look beat up in various other browsers. The scripts you choose will determine compatibility.


Customize The Left Navigation Bar

Customize the contents of the WebLeftBar for each web to include important topics for that web, or to link to an important topic for the overall site. Each web has its own WebLeftBar page. (This is specific to the PatternSkin.)


TIP NOTE: Feel free to add your own tips to TWiki:TWiki.InstantEnhancements as quick notes at the end of the list, following the existing format!

Related Topics: AdminDocumentationCategory

-- Contributors: TWiki:Main.GrantBow, TWiki:Main.LynnwoodBrown, TWiki:Main.MikeMannix, TWiki:Main.PeterMasiar, TWiki:Main.PeterThoeny, TWiki:Main.MattWilkie, TWiki:Main.AmandaSmith

Number of topics: 64

Topic revision: r95 - 2011-07-18 - TWikiContributor
 
This site is powered by the TWiki collaboration platform Powered by Perl This site is powered by the TWiki collaboration platformCopyright © 1999-2024 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback
Note: Please contribute updates to this topic on TWiki.org at TWiki:TWiki.WebHome.